by Derek Hildreth – Technologic Systems
This comprehensive and easy to read example C code is designed to work alone or included as a library for dealing with general purpose I/O via the sysfs interface in Linux. It can easily be applied to any computer which utilizes the GPIO sysfs interface (both pro and maker boards). Getting started is a breeze. You just need to decide if you’re going to use it as a library (including it into your existing code) or as a stand-alone utility. We’ll talk about in this article, but first and foremost, here’s the source code we’ll be working with:
https://github.com/embeddedarm/gpio-sysfs-demo
To get started, download or clone this repository to your board, extract it, and change your directory to it, like so:
wget https://github.com/embeddedarm/gpio-sysfs-demo/archive/master.zip unzip master.zip cd gpio-sysfs-demo-master/
The two important files in this repository came from Technologic System’s GitHub pages:
- https://github.com/embeddedarm/ts4900-utils/blob/master/src/gpiolib.c
- https://github.com/embeddedarm/ts4900-utils/blob/master/src/gpiolib.h
The included Makefile makes quick work out of compiling the example code mentioned in the sections below, as you’ll see soon enough.
Stand-Alone Utility
As a stand-alone utility, you can easily copy the resulting gpioctl program to a directory in your current PATH and include in a script or use it for those one-off commands.
To do this, we’ll simply run sudo make install. The Makefile will compile the standalone utility using (essentially) gcc -D CTL gpiolib.c -o gpioctl and then automatically copy it to /usr/local/bin, which is popularly included in PATH. Then, you can run gpioctl –help for instructions on how to use it. For example, say you want to output logical high on DIO #59. You would first set the DIO to be an output, and then you’d set it. Here’s an example of toggling it:
gpioctl –ddrout 59
gpioctl –setout 59
gpioctl –clrout 59
That’s it! If, say, DIO #59 was tied to an LED, you should see the LED turn on and off again.
Now you can easily include these commands into a bash shell script or Python system call or, well, you get the point.
Pro Tip: Keep in mind, the LED may be active low, so you might actually see the opposite (logic high output turns the LED off, logic low output turns the LED on).
Read more: Robust C Library and Utility for GPIO sysfs Interface in Linux