I have made a simple script that uses when_pressed and when_released to read the value of a GPIO pin and writes it to file. It works as expected when run from terminal, but not when run from rc.local. (I have a couple other python scripts in rc.local that run fine.) I have tried to catch an error by running it like: python3 /home/user/myfile.py > /home/user/errors.txt 2>&1 & but nothing gets written to the file. (If I force an error, it does show up in errors.txt)
The code is as follows:
from gpiozero import Button from signal import pause pin = Button("BOARD7",pull_up=None,active_state=True) def write_0(): with open('/home/user/file.txt', 'w+') as f: f.write('%s\n' %0) f.close() def write_1(): with open('/home/user/file.txt', 'w+') as f: f.write('%s\n' %1) f.close() while True: pin.when_released = write_0 pin.when_pressed = write_1 pause() Replacing the code in the while loop with:
pin.wait_for_press() write_1() pin.wait_for_release() write_0() also doesn't work.
Now, I know that the script is run because I can replace the code in the while loop with:
if pin.is_pressed: write_1() else: write_0() and the file gets updated according to the value of the pin correctly. However, it writes constantly and I would rather it not do that. (sleep is not the solution)
What's causing this? I have not tried running it via the systemd method, mainly because I can't get anything to run...
I did find discussion #1153 on gpiozero's github page. I added os.chdir() before every call to gpiozero, but A - I don't know what directory to set B - it didn't help when I set it to home directory
Operating system: Debian 12 Bookworm Python version: 3.11.2 Pi model: Pi 3 Model B Rev 1.2 GPIO Zero version: 2.0.1 Pin factory used: LGPIO
when_released/when_pressed. Removing the while loop did not fix the issue of the script not running when started from rc.local. I do not have a debounce because I do not need it. I am not reading a physical button.