Hello there,
Switch button with LED indicator |
I had a little bit of fun with the Interrupt Service Routine configuration in the Pi4J exercises that I am currently working on. I am translating from C code exercises into JAVA, just for fun, do not ask much more about the reasons ;-)
I found that an implementation of a button Interrupt Service Routine in Pi4j is not that straight forward as it is for a listener.
First I noticed that if the call back "GpioInterruptCallback" class is not an in line class, the call back wont work and some nasty exception will come from the WiringPi library. Lets say for example that the call back is defined as an inner class or an external class in some other file, it wont work. At least not for me, instead I had to put the callback class as an in line class like this:
Gpio.wiringPiISR(btnPin, Gpio.INT_EDGE_FALLING, new GpioInterruptCallback() {
....
@Override
public void callback(int pin) {
.....
}
....
});
Second for some other reason the declaration of the "Gpio.wiringPiISR(..)" needs to happen in an static method. For example the main() or some other static method. I ended up creating a static method like this:
private static void gpioIsrSetup() {
.....
Gpio.pinMode(btnPin, Gpio.INPUT);
Gpio.pullUpDnControl(btnPin, Gpio.PUD_UP);
Gpio.pinMode(ledPin, Gpio.OUTPUT);
Gpio.pullUpDnControl(ledPin, Gpio.PUD_DOWN);
Gpio.digitalWrite(ledPin, false);
Gpio.wiringPiISR(btnPin, Gpio.INT_EDGE_FALLING, new GpioInterruptCallback() {
.....
}
Finally I added some de-bouncing control software to eliminate the extra events caused by switch bouncing. I think it works quite well, but in summary the listener implementation alternative has a little bit better performance while doing repeated fast switching of the button. However for a normal one-off switch interaction this code works perfectly well.
For more details about the code please see the exercise Ex13_ButtonISR.java and if you want to compare with the listener implementation take a look at the Ex13_ButtonListener.java.
For full details about how to set up your Raspberry Pi and how to run these exercises please check out my old post Raspberri Pi with Pi4j and Junit testing mockups. Or leave me a comment if you have any issue or question.
Many thanks for reading,
Keep on hacking,
Posted by Marc Andreu.
No comments:
Post a Comment