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.
/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.