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", 
cur = db.cursor()

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

  # Define GPIO to use on Pi
  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

 # Send 10us pulse to trigger
 GPIO.output(GPIO_TRIGGER, True)
 # Wait 10us
 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))
        print "Writing to database..."
        # Execute the SQL command
        # Commit your changes in the database
        print "Write Complete"

        # Rollback in case there is any error
        print "Failed writing to database"

   # Reset GPIO settings

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


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.

  • /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 '17 at 22:13
  • @stevieb disregard that last message - found it. Working perfectly no - thanks for the pointer! – StolenSheep May 7 '17 at 22:31

Puting the task in

sudo crontab -e

instead of the regular crontab fixes this permission issue!


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


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, privacy policy and cookie policy

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