Its funny how a single sentence can change your course. In the last post about this work, I said:
We also need to run hass as root, because OrangePi GPIO support requires access to /dev/mem for reasons I haven’t dug into just yet.
That’s turned out to be (reasonably) a pretty big sticking point upstream. Access to /dev/mem gives you a whole bunch of access to the machine that Home Assistant probably shouldn’t have.
Alastair went off spelunking because he’s more patient than me and found yet another OrangePi GPIO library. I think we’re up to three or four of these at the moment, but this is the first one we’ve found which supports the sysfs interface to GPIO pins. That’s exciting because it removes our run-as-root requirement. Its unexciting in that the sysfs interface has been deprecated by the kernel, but will remain supported for a while.
I think people would be within their rights to conclude that the state of GPIO libraries for OrangePi is a bit of a dumpster fire right now.
Anyways, the point of this post is mostly to write down how to use the sysfs interface to GPIO pins so that I can remember it later, I’ll take more about this new library and if it meets our needs in a later post.
The first step is to determine what pin number the GPIO pin is. On the OrangePi these are labelled with names like “PA7”, which is the 7th bit in the “A” GPIO register. To convert that into a pin number as used by sysfs you do this:
def pin_number(letter, digit): return (ord(letter) - ord('A')) * 32 + digit
So, pin_number(‘A’, 7) for PA7 is just … 7.
Note that I now recommend that people use SUNXI pin mapping, as its much less confusing. You can read more about alternative pin mappings in this post of worked OrangePi GPIO examples.
Now we can enable the pin, set it to output, and then blink the LED to prove it works:
# cd /sys/class/gpio # echo 7 > export # cd gpio7 # echo "out" > direction # echo 1 > value # sleep 1 # echo 0 > value
The next step? To make sure that the new GPIO library supports sysfs access to GPIOs on the OrangePi Prime.