1

I've written a small program that spins a motor throughout the day on the Raspberry Pi 2 Model B, using its GPIO pins. The program works perfectly well, and hasn't had any issues with the GPIO pins. After successfully testing the program for a while I decided to add it to the Pi's start up via editing rc.local. Now the program doesn't work properly and the motor doesn't spin at all. Using the command ps -ef | grep python I have determined that the program is being executed. Any thoughts?

Code below:

# -*- coding: utf-8 -*-

import MotorControl
import DateAndTime

import datetime
import time
import RPi.GPIO as GPIO

import os
import glob
import collections

numberOfFeeds = 2; #Storing the number of times the fish are fed per day in a global variable

##Sets up GPIO pins for motor
def establishMotorPins():
    ##Setting up pins and enabling the motor    
    MotorControl.setUpGPIOPins(27, 24, 5)
    GPIO.output(5, GPIO.HIGH)

##Spins the motor - feeding the fish
def feedFish(duration):
    ##print("Feedig time!")    
    MotorControl.motorCycle(27, 24, 'c', duration) #c standing for clockwise

##Write to a log file
def writeToFile(t):
    logFile.write("\nFish have been fed on: " + str(datetime.datetime.now()) +
                  " Tempreature is (°C): " + str(t))
    logFile.flush()
    os.fsync(logFile.fileno())

##Reading tempreature from sensor (tempreature is stored in file)
def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

##Extracting tempreature from reading stored in text file
def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string)/1000.0
        temp_f = temp_c*9.0/5.0 + 32.0
        return temp_c #include ,temp_f to return temp F

##Defining a function as my main method
def main():

    todaysDate = DateAndTime.getTodaysDate()
    time = DateAndTime.getHoursMin()

##Using a try, excpet and for loop to determine position of date value in dictionary
indexOfDate = 0    
for entry in feedingTimes:
    try:
        datetime.datetime.strptime(str(entry), '%Y-%m-%d')
        ##If an exception is not raised, ie value m
    except ValueError:
        indexOfDate += 1

dateInDictionary = feedingTimes.keys()[indexOfDate]

##Checking if the fish have been fed on this date
if(dateInDictionary == todaysDate):
    if(feedingTimes[dateInDictionary] == numberOfFeeds):
        ##Do not do anything if fish have already been fed on this day
        return
    elif(time in feedingTimes  and feedingTimes[time] == False):

        temp = read_temp()
        if(temp < 40):
            feedFish(5)
        ##Updating the dictionary
        feedingTimes[time] = True
        feedingTimes[dateInDictionary] += 1

        writeToFile(temp)
else:

    ##Setting all values in dictionary to False (including date entry)        
    for items in feedingTimes:
        feedingTimes[items] = False

    ##Remove old date entry, adding a new date entry
    del feedingTimes[dateInDictionary]
    feedingTimes[todaysDate] = 0 ##resetting value for number of fish fed

##
##Calling the pre-defined functions
##

##Setting up connection to the tempreature sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'


##Setting up a log file
logFile = open("log.txt", "w") ##use w to write or a to append to file
logFile.write("File created.\nDate and time of creation: " + str(datetime.datetime.now()))
logFile.write("\n-----------------------------------------------------\n")
logFile.flush()
os.fsync(logFile.fileno())


##Creating a dictionary  of feeding times
##0 represents that fish have not been fed on that particular date
##Boolean values represent that fish have not been fed for that particular time
##Using OrderedDict library to ensure that values are stored in the dictionary in the same
##way that they are inserted
feedingTimes = collections.OrderedDict()
feedingTimes[datetime.time(9, 0)] = False
feedingTimes[datetime.time(16, 0)] = False
feedingTimes[datetime.date(2017, 7, 29)] = 0

try:
    establishMotorPins()
#remember to change direction of spin!!!!!    
    while(True):
        main()        
        ##Checking the feeding status every 10seconds    
        time.sleep(10)

    ##Disabiling the motor of - ie setting the enable pin to low
    GPIO.output(5, GPIO.LOW)    
    quit()
except KeyboardInterrupt:
    print("keyboard interrupt detected, program will exit")
except SystemExit:
    print("SystemExit exception caught, program has terminated.")
finally:
    logFile.close()
     GPIO.cleanup()
  • Where is the program listing? How are you starting the program? – joan Aug 31 '17 at 20:42
  • The program would then run as root, something to consider if you've been using a different user. Have you tried sending the output of your command to a log file like this: cmd > log 2>&1. The other possibility would be to use the screen command to launch your command so you can see what happens in the console. – Anonymous Aug 31 '17 at 20:44
  • Code included above, I'm starting the program by simply passing the command: python project.py – edwardam Aug 31 '17 at 20:55
  • I am already using a primitive log file to record ever time the motor spins. However, an entry is added to the file when the motor is supposed to spin but for some reason it doesn't. – edwardam Aug 31 '17 at 20:56
  • When adding scripts to rc.local you may have to specify full paths eg: /usr/bin/python /full/path/to/your/script. – Anonymous Aug 31 '17 at 20:59
0

You'll need to enable autologin in 'raspi-config'. And maybe chmod +x the .py.

Example from my /etc/rc.local:

(sleep 3;su - pi -c "/home/pi/pycam/main.py")&

I hope you'll get this done!

| improve this answer | |

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.