Using Raspberry Pi GPIO Without Python
I’ve been wanting to play with the Raspberry Pi’s GPIO (General Purpose Input/Output) pins for a while now and started googling around for how to do it. As expected, lots of beginner tutorials came up, but they all seemed to require Python, specifically the RPi.GPIO
library. As great as Python is, I wanted to know how to use the pins without Python.
The obvious place to look was the RPi.GPIO library itself. I downloaded the tar.gz of the library (in my case, v0.1.0) and opened up RPi/GPIO/__init__.py
. This version of RPi.GPIO
was super easy to parse. Looking around, I started to see lots of lines like:
with open('/sys/class/gpio/export', 'w') as f:
f.write(id)
I hadn’t explored the /sys/
directory before, but this seemed like what I was looking for. A quick google search led me to this StackOverflow post and the libudev and Sysfs Tutorial. Essentially, /sys/class
contains directories for each class of devices attached to the system. Most of these are actually symlinks to locations in /sys/devices
, which contains the hierarchy of devices as they are attached to the computer.
So, the Python snippet above is writing to files in /sys/class/gpio
, which ultimately controls the pins. Exactly what I was looking for.
With this knowledge, I cd
ed into /sys/class/gpio
to look around. An ls
shows:
export gpiochip0 unexport
Taking the lead from RPi.GPIO
, I chose a pin on the Raspberry Pi (a logical pin, not a physical pin) and exported it:
echo "11" > export
Doing another ls
in the same directory now shows:
export gpio11 gpiochip0 unexport
where gpio11
is a directory. I cd
ed into this directory and did an ls
, which shows:
active_low device direction edge subsystem uevent value
Reading through the Python code, there were only a few things left to do. I wanted to confirm that I could activate this pin through some simple shell commands, so I wired it up with an LED and a resistor so it could function as an output device. Given this, the next step was to provide a direction (which must be one of “in” or “out”; it throws an error otherwise):
echo "out" > direction
And lastly, I needed to set a value to the pin:
echo "1" > value
And the LED turned on.
I’m sure there was a more obvious way I could have figured this all out, but nonetheless I accomplished my goal and learned some cool things in the process. Following the lead of RPi.GPIO
, it’d be easy to implement GPIO in any other language, or perhaps even expand upon the use of /sys/class
to interact with other devices.