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.
Revision 3:896a932d47fc, committed 2022-10-06
- Comitter:
- a_ferguson
- Date:
- Thu Oct 06 16:36:02 2022 +0000
- Parent:
- 2:af576070220a
- Commit message:
- Complete version to be graded (fixed switch bouncing issue)
Changed in this revision
| main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/main.cpp Thu Oct 06 14:44:47 2022 +0000
+++ b/main.cpp Thu Oct 06 16:36:02 2022 +0000
@@ -1,25 +1,30 @@
#include "mbed.h"
-Serial pc(USBTX,USBRX); //do not need when we aren't communicating with pc
-DigitalOut myled1(LED1);
+Serial pc(USBTX,USBRX); // do not need when we aren't communicating with pc
+DigitalOut myled1(LED1); //LEDs 1 and 2
DigitalOut myled2(LED2);
DigitalIn button(p17); // button attached to p17
+Timer led2timer; // create timer
int main() {
-int currentstate=0;
+int currentstate=0; // set variables as integers
int previousstate=0;
int counter=0;
+led2timer.start(); // starts timer
+
while(1) {
currentstate=button.read(); // set current state
- if (currentstate==1){ //blinks 1s interval when pressed
- myled2=!myled2;
- wait(1);
+ if (currentstate==1){ // button pressed
+ if (led2timer.read()>=1){ // blinks 1s interval when pressed
+ myled2=!myled2;
+ led2timer.reset(); // reset timer
+ }
- if (currentstate==previousstate){
+ if (currentstate==previousstate){ // no change
}
else{ // change in state adds counter
@@ -27,13 +32,15 @@
pc.printf("count=%i \r\n",counter);
}
- } //if
+ } // if
- else { //blinks 0.3s interval when released
- myled2=!myled2;
- wait(0.3);
+ else { // button released
+ if (led2timer.read()>=0.3){ // blinks 0.3s interval when released
+ myled2=!myled2;
+ led2timer.reset(); // reset timer
+ }
- if (currentstate==previousstate){
+ if (currentstate==previousstate){ // no change
}
else{ // change in state adds counter
@@ -41,14 +48,17 @@
pc.printf("count=%i \r\n",counter);
}
- } //else
+ } // else
if (counter==10){ // counter reaches 10 turns on led1
myled1=1;
- } //if
+ } // if
- previousstate=currentstate; //set previous state
+ previousstate=currentstate; //set previous state at loop end
- } //while
+ wait(0.1); // prevents the counter from counting switch bounces
+ // wait is ok because it it shorter than the timer 0.3
+
+ } // while
-} //main
+} // main