Search the web, and you’ll find quite a few pages discussing the HC-SR04 ultrasonic distance sensor. It is cheap, easy to configure and great for experimenting or non crucial measuring jobs. When used on the Raspberry Pi, however, almost all examples I have seen force you to run the sensor application as superuser (sudo). This means that the entire application has elevated privileges. In general, this is not a good idea.
Search as I might, I was not able to find an example of a non sudo application that used an interrupt where timing was crucial. So I decided to do some research to find a way around this.
Background: I am trying to add distance measurement capability to my Pi, which already does temperature measurements and tracks the sump pump level using a second Pi. All this is done without using ‘sudo’, and since the new functionality is to be integrated into the existing functionality I had to find a solution. I am using Python 2.7 as my main development language.
I am using wiringPi in the existing setup, but it does not handle interrupts. So a Google search is next.
First, I found an article in the November 2012 edition of MagPi by Richard Ryniker entitled ‘GPIO and Interrupts’, which gave a good overview of sudo, interrupts and the like. You can read a pure text version of the article here, without having to look up the magazine version.
The first thing to take away from that is that if you want to use GPIO pins without using sudo you need to download and compile gpio_control.c from Richard’s site. All the instructions on how to compile and then copy and chmod the executable are embedded in the text of the download.
Once you have done that, then you can give a command like this
$ gpio_control export 23
which simply means any user can now use pin 23 without using sudo
To revert control once you do not need this anymore:
$ gpio_control unexport 23
Next, I studied his application for the maximum LED blink rate in Python. This explains how to write a value to a pin. After that, I studied his interrupt example, showing how to detect when a designated pin goes high (or low), i.e how to read the value of a pin.
I then modified the ultrasonic sensor ‘sudo’ application that Matt Hawkins wrote over at Raspberry Pi Spy, to account for the new sudo free approach using interrupts. When running the sudo version and this version, the results are virtually identical, any differences are probably due to the CPU load at that very instant.
Here is the application:
In theory, using interrupts is cleaner and leaner than the old way where the application sits in a loop, uses a lot of CPU cycles to check continuously whether or not the state of the pin has changed.