When I last wrote about using the Raspberry Pi 3’s GPIO pins, it was with my simple and silly cylon.js application (see “retesting gpio with node.js and onoff with the raspberry pi 3“). Every time I ran that application, or any other application that used the GPIO pins, I had to run as root or use sudo (to run as temporary root):
sudo node cylon.js
That kicked off the application and allowed me to flash those LEDs back and forth.
Turns out that there’s a straightforward way to do all this without root or rootly powers, using the granularity built into Linux. These are the straightforward steps to run GPIO applications as a regular user. Note that I’m using Arch Linux and the account is ‘alarm’. The following changes are made as root (su to root).
- As root create a new group called gpio (groupadd -f -r gpio)
- As root add the group to the alarm account (usermod -G gpio alarm)
- As root create a udev rules file at /dev/gpiomem in /etc/udev/rules.d/99-gpio.rules
The rules to be placed into the 99-gpio.rules file are:
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'"
Once all the group and account changes have been made and the rules have been added, reboot the Raspberry Pi.
The two key features to making this work are (1) the new group, gpio, and (2) the udev rules that allow anyone who is a member of the gpio group to access /dev/gpiomem, where the GPIO pins are individually accessed. With these changes in place I no longer have to run as root or type ‘sudo’ before any application that accesses the pins because the alarm account is now a member of the gpio group.
There may very well be an Arch Linux package that does all this for you automatically, but I haven’t found it yet.
You must be logged in to post a comment.