Reputation: 1684
I am using a Raspberry Pi 3 model B.
I tried different approaches using both gpiozero
and RPi.GPIO
. The problem occurs regardless of the library used.
Here is an example of code that fails with gpiozero
.
from gpiozero import Button
from signal import pause
def handle():
print("Pressed!")
button = None
while not button:
try:
button = Button(4, pull_up=True)
button.when_pressed = handle
except RuntimeError as e:
print(e)
pass
pause()
The line button = Button(4, pull_up=True)
always raises a RuntimeError
and the output of the program (running python3
) is:
Failed to add edge detection
Failed to add edge detection
Failed to add edge detection
Failed to add edge detection
# ... it goes on for ages
I already tried to reinstall RPi.GPIO
and gpiozero
but it did not help.
Here is the full traceback of the exception
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/gpiozero/input_devices.py", line 84, in __init__
self.pin.when_changed = self._fire_events
File "/usr/lib/python3/dist-packages/gpiozero/pins/__init__.py", line 240, in <lambda>
lambda self, value: self._set_when_changed(value),
File "/usr/lib/python3/dist-packages/gpiozero/pins/rpigpio.py", line 233, in _set_when_changed
bouncetime=self._bounce)
RuntimeError: Failed to add edge detection
Upvotes: 2
Views: 9096
Reputation: 5125
I also get the same problem on Raspberry Pi 3 B with Arch_arm operating system.
It seems that this problem has nothing to do with your Python code.
In Raspberrypi/linux system, you can only use the GPIO with root authority by default.
The /dev/gpiomem
instead of /dev/mem
, can let user use GPIO with rootless. Of course you should make some changes.
add new group name gpio
&& add your user account name to the group
sudo groupadd -r gpio
sudo usermod -a -G gpio pi
add udev rules to /etc/udev/rules.d/
ls -l /etc/udev/rules.d
-rw-r--r-- 1 root root 580 Aug 5 15:02 raspberrypi.rules
You can add these rules below to the tail of the file raspberrypi.rules
with sudo.
SUBSYSTEM=="bcm2835-gpiomem", KERNEL=="gpiomem", GROUP="gpio", MODE="0660"
SUBSYSTEM=="gpio", KERNEL=="gpiochip*", ACTION=="add", PROGRAM="/bin/sh -c 'chown root:gpio /sys/class/gpio/export /sys/class/gpio/unexport ; chmod 220 /sys/class/gpio/export /sys/class/gpio/unexport'"
SUBSYSTEM=="gpio", KERNEL=="gpio*", ACTION=="add", PROGRAM="/bin/sh -c 'chown root:gpio /sys%p/active_low /sys%p/direction /sys%p/edge /sys%p/value ; chmod 660 /sys%p/active_low /sys%p/direction /sys%p/edge /sys%p/value'"
Happy coding.
Upvotes: 3
Reputation: 141
running it with sudo
should work
For example
sudo python test-gpio.py
Upvotes: 0