/////////////////////////////////// // // lab4_base project // // created 7/13/21 by tj // rev 0 // /////////////////////////////////// // // Base program for Lab 4 // // interrupt based counter with debounce // that flashes an LED based on the current count value // /////////////////////////////////// #include "mbed.h" #include #define T_FLASH 250000 // in us - 0.25s #define T_BOUNCE 5000 // in us - 5ms #define T_WAIT 4000000 // in us - 4 sec // function prototypes (declaration) void counter_isr(void); void flash_led(volatile int * cnt_ptr); // Global HARDWARE Objects // create an interrupt object for Pin D4 InterruptIn Button(D4); // create an output object for pin D5 for the LED DigitalOut MyLED(D5); // global variables for ISR // note it is defined as volatile since it can // change without main knowing it - volatile // forces it to be read from memory each time // instead of from a CPU register volatile int cnt; int main(void){ setbuf(stdout, NULL); // disable buffering // splash printf("\n\nLab4_base - example for EE2905\n"); printf("Using Mbed OS version %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION); // attach the isr Button.fall(&counter_isr); // initialize the count cnt = 0; // intilaize the led to off MyLED.write(0); // create a waiting loop while(1){ wait_us(T_WAIT); printf("The current count is: %i\n", cnt); flash_led(&cnt); } // end while return 0; }// end main void flash_led(volatile int * cnt_ptr){ // assume LED is already off so can just toggle int i; for(i = 0; i < (2 * *cnt_ptr); i++){ MyLED.write(!MyLED.read()); wait_us(T_FLASH); }// end for return; }// end flash_led void counter_isr(void){ // interrupt service routine for counter // debounces the pin and increments the cnt /////////////////////////////////// // Debounce section // uint8_t pinval_1; uint8_t pinval_2; uint8_t valid; // first check pinval_1 = Button.read(); // allow bounce to complete wait_us(T_BOUNCE); // debounce // terrible way to solve the problem // second check pinval_2 = Button.read(); // set "valid" if not a bounce and value is 0 if(pinval_1 == pinval_2) valid = !pinval_1; // /////////////////////////////////////// /////////////////////////////////////// // counter increment section // // increment if valid cnt += valid; // /////////////////////////////////////// return; } // end counter_isr