lab 2 program A

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_G(PTD0);
00010 InterruptIn button_B(PTD5);
00011 
00012 DigitalOut led_G(LED_GREEN);
00013 DigitalOut led_B(LED_BLUE);
00014 
00015 volatile int pressEvent_G = 0 ;
00016 volatile int pressEvent_B = 0 ;
00017 
00018 // This function is invoked when then interrupt occurs
00019 //   Signal that the button has been pressed
00020 //   Note: bounce may occur 
00021 void buttonCallback_G(){
00022     pressEvent_G = 1 ;
00023 }
00024 
00025 void buttonCallback_B(){
00026     pressEvent_B = 1 ;
00027 }
00028 
00029 /*  ---- Main function (default thread) ----
00030     Note that if this thread completes, nothing else works
00031  */
00032 int main() {
00033     button_G.mode(PullUp);             // Ensure button i/p has pull up
00034     button_G.fall(&buttonCallback_G) ;   // Attach function to falling edge
00035 
00036     button_B.mode(PullUp);             // Ensure button i/p has pull up
00037     button_B.fall(&buttonCallback_B) ;   // Attach function to falling edge
00038 
00039     //int counter_G = 2;
00040     //int rate_G = 1;
00041     
00042     //int counter_B = 2;
00043     //int rate_B = 1;    
00044     
00045     bool on_G = 0;
00046     bool on_B = 0;
00047 
00048     while(true) {
00049         // Toggle the Green LED every time the button is pressed
00050         if (pressEvent_G) {
00051             //led_G = !led_G ;
00052             pressEvent_G = 0 ; // Clear the event variable
00053             on_G = !on_G;
00054         }
00055         
00056         // Toggle the Green LED every time the button is pressed
00057         if (pressEvent_B) {
00058             //led_B = !led_B ;
00059             pressEvent_B = 0 ; // Clear the event variable
00060             on_B = !on_B;
00061         }
00062         
00063         led_G = (!led_G)|on_G;
00064         led_B = (!led_B)|on_B;
00065         
00066         wait(0.5) ;
00067     }
00068 }