Implemented interrupt code to handle presses of two buttons and control 2 leds separately.
Fork of digitalInInterrupt_sample by
Revision 4:c8b84240732a, committed 2018-02-01
- Comitter:
- natgovor
- Date:
- Thu Feb 01 12:30:18 2018 +0000
- Parent:
- 3:05b6a1431a6b
- Commit message:
- Implemented interrupt code to handle presses of two buttons and control 2 leds separately.
Changed in this revision
main.cpp | Show annotated file Show diff for this revision Revisions of this file |
diff -r 05b6a1431a6b -r c8b84240732a main.cpp --- a/main.cpp Tue Jan 16 18:14:21 2018 +0000 +++ b/main.cpp Thu Feb 01 12:30:18 2018 +0000 @@ -6,31 +6,71 @@ // is pressed // The callback uses a shared variable to signal another thread -InterruptIn button(PTD0); -DigitalOut led(LED_GREEN); +InterruptIn redButton(PTD0); +InterruptIn blueButton(PTD5); +DigitalOut redLed(LED_RED); +DigitalOut blueLed(LED_BLUE); -volatile int pressEvent = 0 ; +volatile int redPressEvent = 0; +volatile int bluePressEvent = 0; // This function is invoked when then interrupt occurs // Signal that the button has been pressed // Note: bounce may occur -void buttonCallback(){ - pressEvent = 1 ; +void redButtonCallback(){ + redPressEvent = 1 ; +} + +void blueButtonCallback(){ + bluePressEvent = 1 ; } /* ---- Main function (default thread) ---- Note that if this thread completes, nothing else works */ int main() { - button.mode(PullUp); // Ensure button i/p has pull up - button.fall(&buttonCallback) ; // Attach function to falling edge + // LEDa are on by default + redLed = 0; + blueLed = 0; + + int flashPeriod = 5; + int redBtnCounter = flashPeriod; + int blueBtnCounter = flashPeriod; + + bool redIsFlashing = true; + bool blueIsFlashing = true; + + redButton.mode(PullUp); // Ensure button i/p has pull up + redButton.fall(&redButtonCallback) ; // Attach function to falling edge + blueButton.mode(PullUp); // Ensure button i/p has pull up + blueButton.fall(&blueButtonCallback) ; // Attach function to falling edge while(true) { - // Toggle the LED every time the button is pressed - if (pressEvent) { - led = !led ; - pressEvent = 0 ; // Clear the event variable + Thread::wait(100); + if (redIsFlashing) { + redBtnCounter--; + } + if (blueIsFlashing) { + blueBtnCounter--; + } + + if (redBtnCounter == 0) { + redLed = !redLed; + redBtnCounter = flashPeriod; } - Thread::wait(100) ; + if (blueBtnCounter == 0) { + blueLed = !blueLed; + blueBtnCounter = flashPeriod; + } + + // Stop flashing (freeze in the current state) every time the button is pressed + if (redPressEvent) { + redIsFlashing = !redIsFlashing; + redPressEvent = 0; // Clear the event variable + } + if (bluePressEvent) { + blueIsFlashing = !blueIsFlashing; + bluePressEvent = 0; // Clear the event variable + } } } \ No newline at end of file