1

I've got a python script on my Pi 3 to read a value from an ultra-sonic sensor then write to a db - that alls grand. I've tried to make a crontab task scheduler for it, but it's not working.

First, the script:

#!/usr/bin/env python

import os
import time
import RPi.GPIO as GPIO
import datetime
import glob
import MySQLdb
from time import strftime

# Variables for MySQL
db = MySQLdb.connect(host="localhost", user="root",passwd="123", 
db="temp_database")
cur = db.cursor()

def distanceRead():
  # Use BCM GPIO references
  # instead of physical pin numbers
  GPIO.setmode(GPIO.BCM)

  # Define GPIO to use on Pi
  GPIO_TRIGGER = 23
  GPIO_ECHO    = 24

  # Speed of sound in cm/s at temperature
  temperature = 20
  speedSound = 33100 + (0.6*temperature)

  # Set pins as output and input
  GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
  GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

 # Set trigger to False (Low)
 GPIO.output(GPIO_TRIGGER, False)

 # Allow module to settle
 time.sleep(0.5)

 # Send 10us pulse to trigger
 GPIO.output(GPIO_TRIGGER, True)
 # Wait 10us
 time.sleep(0.00001)
 GPIO.output(GPIO_TRIGGER, False)
 start = time.time()

 while GPIO.input(GPIO_ECHO)==0:
    start = time.time()

 while GPIO.input(GPIO_ECHO)==1:
  stop = time.time()

 # Calculate pulse length
 elapsed = stop-start

 # Distance pulse travelled in that time is time
 # multiplied by the speed of sound (cm/s)
 distance = elapsed * speedSound

 # That was the distance there and back so halve the value
 distance = distance / 2

 return round(distance, 1)

while True:
    distanceRounded = distanceRead()
    print distanceRounded
    datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
    print datetimeWrite
    sql = ("""INSERT INTO distanceLog (datetime,distance) VALUES (%s,%s)""",(datetimeWrite,distanceRounded))
    try:
        print "Writing to database..."
        # Execute the SQL command
        cur.execute(*sql)
        # Commit your changes in the database
        db.commit()
        print "Write Complete"

    except:
        # Rollback in case there is any error
        db.rollback()
        print "Failed writing to database"

    cur.close()
    db.close()
   # Reset GPIO settings
   GPIO.cleanup()
   break

I used

crontab -e

to get into my crontab file and and put this second task at the end of the file(the other task is running perfectly, by the way):

  */5 * * * * /home/pi/tempLog/readTempSQL.py
  */1 * * * * /home/pi/distanceLog/ultrasonicReader.py

I put in this command (I ran it from the folder the .py file is in, but does that even matter?)

  sudo chmod +x ultrasonicReader.py

and tried to test it with

   ./ultrasonicReader.py

but I get this error message -

   Traceback (most recent call last):
     File "./ultrasonicReader.py", line 64, in <module>
    distanceRounded = distanceRead()
     File "./ultrasonicReader.py", line 29, in distanceRead
     GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
   RuntimeError: No access to /dev/mem.  Try running as root!

Any idea what I need to do to give the correct permission to let it run the script? If I use the sudo command on the line above it works fine, so I can only assume it's a permission issue rather than a code one? I assume I'd need to change the permissions on /dev/mem, but how?

The file ultasonicReader.py is definitely in /home/pi/distanceLog by the way.

2
  • /dev/mem is only accessible by the superuser. Either modify the script to not use that, wrap those parts with code that elevates system access, or run as the root user.
    – stevieb
    May 7, 2017 at 22:13
  • @stevieb disregard that last message - found it. Working perfectly no - thanks for the pointer! May 7, 2017 at 22:31

3 Answers 3

2

Puting the task in

sudo crontab -e

instead of the regular crontab fixes this permission issue!

3
  • Please accept your answer with a click on the tick on its left side. Only this will finish the question and it will not pop up again and again for years.
    – Ingo
    Dec 7, 2019 at 12:05
  • the sudo chmod +x ultrasonicReader.py also seemed to be important
    – Norfeldt
    May 29, 2020 at 8:40
  • This is the correct answer; don't use sudo in a program run from a user crontab (i.e. user pi). Don't change permissions on resources you didn't create (e.g. /dev/mem - they are restricted for a reason.
    – Seamus
    Jan 26, 2022 at 12:06
-1

Try the following

sudo su 
crontab -e

Then put crontab here

sudo  ./ultrasonicReader.py

This should work or switch to root user with sudo s

-1

Have you tried adding this? I've also added ampersands but have read in a few places that this is no longer required to make cronjobs run in the background.

*/5 * * * * sudo python /home/pi/templog/readTempSQL.py &
*/1 * * * * sudo python /home/pi/distanceLog/ultrasonicReader.py &

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.