Alif Ahmed / Mbed OS digitalInInterrupt_sample_program
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002  
00003 // Labs 2: Example program for using an interrupt (or callback)
00004 // -----------------------------------------------------------
00005 // A callback function (corresponding to an ISR) is called when a button 
00006 //    is pressed
00007 // The callback uses a shared variable to signal another thread
00008 
00009 InterruptIn button(PTD0);  // Pin must be on ports A or D
00010 DigitalOut led(LED_GREEN);
00011 
00012 volatile int pressEvent = 0 ;
00013 
00014 // This function is invoked when then interrupt occurs
00015 //   Signal that the button has been pressed
00016 //   Note: bounce may occur 
00017 void buttonCallback(){
00018     pressEvent = 1 ;  
00019 }
00020 
00021 /*  ---- Main function (default thread) ----
00022     Note that if this thread completes, nothing else works
00023  */
00024 int main() {
00025     button.mode(PullUp);             // Ensure button i/p has pull up
00026     button.fall(&buttonCallback) ;   // Attach function to falling edge
00027 
00028     while(true) {
00029         // Toggle the LED every time the button is pressed
00030         if (pressEvent) {
00031             led = !led ;
00032             pressEvent = 0 ; // Clear the event variable
00033         }
00034         ThisThread::sleep_for(100) ; // delay for 100ms 
00035     }
00036 }