Raspberry Pi IoT In C - Events & Interrupts |
Written by Harry Fairhead | ||||||||
Monday, 02 November 2020 | ||||||||
Page 4 of 4
An Edgy ButtonTo make the difference between reading the line to detect a change of state and using the events, let’s consider another version of our button program given earlier. In this case the GPIO line is set up for input and a message to press the button is printed. Then the program waits for 20 seconds and finally tests the state of the line. Even if the user has pressed the button lots of times during the 20 seconds, all that matters is the final state of the line as read when the sleep(20) ends: #include <stdio.h> #include <stdlib.h> #include <bcm2835.h> #include <unistd.h> int main(int argc, char** argv) { if (!bcm2835_init()) return 1; bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, In other words, this program misses any button presses during the 20 second pause. Now compare this to the same program but using edge events: #include <stdio.h> #include <stdlib.h> #include <bcm2835.h> #include <unistd.h> int main(int argc, char** argv) { if (!bcm2835_init()) return 1; bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, In this case the GPIO line is set up as an output with a pull-up and it fires an event on the falling edge of a signal. Notice that now the if statement tests not the state of the line, but the state of the event flag. The difference is that if the user presses the button at any time during the 20-second sleep, the flag is set and the program registers the button press. The flag is set no matter what the program is doing, so instead of sleeping it could be getting on with some work, confident that it won’t miss a button press. However, it cannot know exactly when the button was pressed and it cannot know how many times the button was pressed. Events allow you to avoid missing a single input while polling, but cannot handle multiple inputs. You could implement a full queue-based event handling system, but this would only make sense on a multi-core machine like a Pi 4 and with the thread running the event detection locked into a separate core from the rest of the program. This probably isn’t worth the effort. A more reasonable alternative is to use the interrupt abilities of the GPIO character driver. In chapter but not in this extract:
Summary
Raspberry Pi And The IoT In C Second EditionBy Harry FairheadBuy from Amazon. Contents
<ASIN:1871962633> <ASIN:B08KLNT2JC> To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
||||||||
Last Updated ( Saturday, 07 November 2020 ) |