How to use Kernel GPIO interrupts on the Raspberry Pi

Posted by

Presumably everyone knows what the Raspberry Pi is, by now, so I’ll not start there. You may or may not know that the RasPi has General Purpose Input/OutputWikipedia: A general-purpose input/output (GPIO) is an uncommitted digital signal pin on an integrated circuit or electronic circuit board which may be used as an input or output, or both, and is controllable by... (GPIO) pins as standard. Some of these provide 3.3v power, some provide 5v power, some are grounded and the others can be used for input and output. Pins will output 3.3v when connected to ground and will be ‘raised’ as ‘on’ when 3.3v is supplied to them. You change, in software, whether a pin is input or output. Simplez.

The Raspbian distribution has, since around mid 2012, had a kernel which includes support for Kernel GPIO interrupts. The advantages of using these over a traditional poll loop are that response times are faster and CPU is not consumed whilst idle. To test this, I rigged up a small switch circuit on a breadboard. A diagram is as follows:

Raspberry Pi Switch Circuit Diagram
Raspberry Pi Switch Circuit Diagram

Details on the pinout of the RasPi’s GPIO can be found here. This should give you an idea on where to connect the circuit. The code described below uses GPIO 21 (GPIO 27 on rev 2 devices). This is mapped to GPIO 2 in the WiringPi library.

The C code to handle this can be found on my GitHub account under the Raspberry Pi GPIO Interrupt repo. Compilation instructions are in the readme. It’s designed to act as an example though should work out the box. Be sure to tweak the PIN and¬†IGNORE_CHANGE_BELOW_USEC constants to suit your hardware.¬†10000 micro seconds worked well for my “switch” which was rather just 2 bits of wire touched together. Better switches may cause less jitter.

Leave a Reply

Your email address will not be published. Required fields are marked *