Search code examples
pythonlinuxraspberry-piraspbianstartup

Python script doesn't start on boot


I have a python script in my Raspberry Pi that is connected to a rain gauge. When the rain gauge detects rain, the script shows 0.2 and write it to file. This is the code:

#!/usr/bin/env python3
import time
import RPi.GPIO as GPIO
BUTTON_GPIO = 16

if __name__ == '__main__':
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    pressed = False
    while True:
        # button is pressed when pin is LOW
        if not GPIO.input(BUTTON_GPIO):
            if not pressed:
                print("0.2")
                pressed = True
        # button not pressed (or released)
        else:
            pressed = False
        time.sleep(0.1)

My idea is to use a code like that to save the total amount of rain. When the python script show 0.2 > write it to file.

python3 rain.py >> rain.txt

The code creates a file but doesn't write anything until execution is finished by Ctrl + C.

I need to execute it on boot. I have tried to add it to crontab and rc.local but doesn't work.

I tried to execute it with sudo and pi. The permissions are 755.

Thank you!


Solution

  • try this

    import time
    import RPi.GPIO as GPIO
    BUTTON_GPIO = 16
    
    if __name__ == '__main__':
        outputfile=open("/var/log/rain.txt","a",0)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        pressed = False
        while True:
            # button is pressed when pin is LOW
            if not GPIO.input(BUTTON_GPIO):
                if not pressed:
                    openputfile.write("0.2\n")
                    pressed = True
            # button not pressed (or released)
            else:
                pressed = False
            time.sleep(0.1)
    

    open a file in append mode with non buffered write. Then when an event occurs, write to that file.

    Do not use shell redirect as it will (in this case) buffer all the program output until exit and then write to a file. Of course, the exit never happens as you have a "while True" with no break