noop din
/
digitalInInterrupt_sample
interrupt for lab2
Fork of digitalInInterrupt_sample by
Diff: main.cpp
- Revision:
- 1:13e0c1956b54
- Parent:
- 0:a66a8cb0012c
- Child:
- 2:071f22412cdc
diff -r a66a8cb0012c -r 13e0c1956b54 main.cpp --- a/main.cpp Mon Jan 23 13:53:49 2017 +0000 +++ b/main.cpp Mon Jan 23 17:26:17 2017 +0000 @@ -1,65 +1,39 @@ #include "mbed.h" #include "rtos.h" -// Labs 2: Example program for polling an input -// -------------------------------------------- -// The program uses a thread to poll a digital input -// - The thread monitors the position of the button -// - When the button transitions up and down, a press event is signaled -// - Button bounce is guarded against -// A second thread checks for the press event and toggles the LED +// Labs 2: Example program for using an interrupt (or callback) +// ----------------------------------------------------------- +// A callback function (corresponding to an ISR) is called when a button +// is pressed +// The callback uses a shared variable to signal another thread -DigitalIn button(PTD0, PullUp); +InterruptIn button(PTD0); DigitalOut led(LED_RED); -Thread pollT ; // thread to poll -Thread flashT ; // thread to flash light -volatile int pressEvent = 0 ; // Variabe set by the polling thread +Thread flashT ; +volatile int pressEvent = 0 ; -enum buttonPos { up, down, bounce }; // Button positions -void polling() { - buttonPos pos = up ; - int bcounter = 0 ; - while (true) { - switch (pos) { - case up : - if (button == 1) { // now down - pressEvent = 1 ; // transition occurred - pos = down ; - } - break ; - case down : - if (button == 0) { // no longer down - bcounter = 3 ; // wait four cycles - pos = bounce ; - } - break ; - case bounce : - if (button == 1) { // down again - button has bounced - pos = down ; // no event - } else if (bcounter == 0) { - pos = up ; // delay passed - reset to up - } else { - bcounter-- ; // continue waiting - } - break ; - } - Thread::wait(30); - } +// Signal when the button is pressed +// Note: bounce may occur +void buttonCallback(){ + pressEvent = 1 ; } // Toggle the LED every time the button is pressed +// Note: the LED could be toggled in the callback void flash() { while(true) { if (pressEvent) { - pressEvent = 0 ; // clear the event variable led = !led ; + pressEvent = 0 ; // Clear the event variable } Thread::wait(100) ; } } int main() { - pollT.start(&polling) ; // start the polling thread running - flashT.start(&flash) ; // start the flashing thread running + button.mode(PullUp); // Ensure button i/p has pull up + button.rise(&buttonCallback) ; // Attach function to rise event + + flashT.start(&flash) ; // Start the flashing thread running } \ No newline at end of file