Lab 2 sample 2: use of interrupts
Dependents: digitalInInterrupt_sample
Fork of digitalInPolling_sample by
main.cpp@5:86742cfaf4e4, 2020-01-30 (annotated)
- Committer:
- WilliamMarshQMUL
- Date:
- Thu Jan 30 08:16:04 2020 +0000
- Revision:
- 5:86742cfaf4e4
- Parent:
- 4:728667196916
Replace wait with sleep_for
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
WilliamMarshQMUL | 0:a66a8cb0012c | 1 | #include "mbed.h" |
WilliamMarshQMUL | 0:a66a8cb0012c | 2 | |
WilliamMarshQMUL | 1:13e0c1956b54 | 3 | // Labs 2: Example program for using an interrupt (or callback) |
WilliamMarshQMUL | 1:13e0c1956b54 | 4 | // ----------------------------------------------------------- |
WilliamMarshQMUL | 1:13e0c1956b54 | 5 | // A callback function (corresponding to an ISR) is called when a button |
WilliamMarshQMUL | 1:13e0c1956b54 | 6 | // is pressed |
WilliamMarshQMUL | 1:13e0c1956b54 | 7 | // The callback uses a shared variable to signal another thread |
WilliamMarshQMUL | 0:a66a8cb0012c | 8 | |
WilliamMarshQMUL | 5:86742cfaf4e4 | 9 | InterruptIn button(PTD0); // Pin must be on ports A or D |
WilliamMarshQMUL | 3:05b6a1431a6b | 10 | DigitalOut led(LED_GREEN); |
WilliamMarshQMUL | 0:a66a8cb0012c | 11 | |
WilliamMarshQMUL | 1:13e0c1956b54 | 12 | volatile int pressEvent = 0 ; |
WilliamMarshQMUL | 0:a66a8cb0012c | 13 | |
WilliamMarshQMUL | 3:05b6a1431a6b | 14 | // This function is invoked when then interrupt occurs |
WilliamMarshQMUL | 3:05b6a1431a6b | 15 | // Signal that the button has been pressed |
WilliamMarshQMUL | 1:13e0c1956b54 | 16 | // Note: bounce may occur |
WilliamMarshQMUL | 1:13e0c1956b54 | 17 | void buttonCallback(){ |
WilliamMarshQMUL | 5:86742cfaf4e4 | 18 | pressEvent = 1 ; |
WilliamMarshQMUL | 0:a66a8cb0012c | 19 | } |
WilliamMarshQMUL | 0:a66a8cb0012c | 20 | |
WilliamMarshQMUL | 3:05b6a1431a6b | 21 | /* ---- Main function (default thread) ---- |
WilliamMarshQMUL | 3:05b6a1431a6b | 22 | Note that if this thread completes, nothing else works |
WilliamMarshQMUL | 3:05b6a1431a6b | 23 | */ |
WilliamMarshQMUL | 3:05b6a1431a6b | 24 | int main() { |
WilliamMarshQMUL | 3:05b6a1431a6b | 25 | button.mode(PullUp); // Ensure button i/p has pull up |
WilliamMarshQMUL | 3:05b6a1431a6b | 26 | button.fall(&buttonCallback) ; // Attach function to falling edge |
WilliamMarshQMUL | 3:05b6a1431a6b | 27 | |
WilliamMarshQMUL | 0:a66a8cb0012c | 28 | while(true) { |
WilliamMarshQMUL | 3:05b6a1431a6b | 29 | // Toggle the LED every time the button is pressed |
WilliamMarshQMUL | 0:a66a8cb0012c | 30 | if (pressEvent) { |
WilliamMarshQMUL | 0:a66a8cb0012c | 31 | led = !led ; |
WilliamMarshQMUL | 1:13e0c1956b54 | 32 | pressEvent = 0 ; // Clear the event variable |
WilliamMarshQMUL | 0:a66a8cb0012c | 33 | } |
WilliamMarshQMUL | 5:86742cfaf4e4 | 34 | ThisThread::sleep_for(100) ; // delay for 100ms |
WilliamMarshQMUL | 0:a66a8cb0012c | 35 | } |
WilliamMarshQMUL | 0:a66a8cb0012c | 36 | } |