Program follows assignment specifications. Counter counts each switch state change so ten counts is only five button presses and releases. Wait function is used to avoid counting switch bounces.
main.cpp
00001 #include "mbed.h" 00002 00003 Serial pc(USBTX,USBRX); // do not need when we aren't communicating with pc 00004 DigitalOut myled1(LED1); //LEDs 1 and 2 00005 DigitalOut myled2(LED2); 00006 DigitalIn button(p17); // button attached to p17 00007 Timer led2timer; // create timer 00008 00009 int main() { 00010 00011 int currentstate=0; // set variables as integers 00012 int previousstate=0; 00013 int counter=0; 00014 00015 led2timer.start(); // starts timer 00016 00017 while(1) { 00018 00019 currentstate=button.read(); // set current state 00020 00021 if (currentstate==1){ // button pressed 00022 if (led2timer.read()>=1){ // blinks 1s interval when pressed 00023 myled2=!myled2; 00024 led2timer.reset(); // reset timer 00025 } 00026 00027 if (currentstate==previousstate){ // no change 00028 } 00029 00030 else{ // change in state adds counter 00031 counter=counter+1; 00032 pc.printf("count=%i \r\n",counter); 00033 } 00034 00035 } // if 00036 00037 else { // button released 00038 if (led2timer.read()>=0.3){ // blinks 0.3s interval when released 00039 myled2=!myled2; 00040 led2timer.reset(); // reset timer 00041 } 00042 00043 if (currentstate==previousstate){ // no change 00044 } 00045 00046 else{ // change in state adds counter 00047 counter=counter+1; 00048 pc.printf("count=%i \r\n",counter); 00049 } 00050 00051 } // else 00052 00053 if (counter==10){ // counter reaches 10 turns on led1 00054 myled1=1; 00055 } // if 00056 00057 previousstate=currentstate; //set previous state at loop end 00058 00059 wait(0.1); // prevents the counter from counting switch bounces 00060 // wait is ok because it it shorter than the timer 0.3 00061 00062 } // while 00063 00064 } // main
Generated on Thu Oct 6 2022 21:00:29 by
1.7.2