Lab 2 program b
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 00003 // Labs 2: Example program for polling an input 00004 // -------------------------------------------- 00005 // The program uses a thread to poll a digital input 00006 // - The thread monitors the position of the button 00007 // - When the button transitions up and down, a press event is signaled 00008 // - Button bounce is guarded against 00009 // A second thread (the default one) checks for the press event and toggles the LED 00010 00011 DigitalIn b1(PTD0, PullUp); 00012 DigitalOut led(LED1); 00013 00014 Thread pollT ; // thread to poll 00015 volatile int pressEvent = 0 ; // Variabe set by the polling thread 00016 00017 enum buttonPos { up, down, bounce }; // Button positions 00018 void polling() { 00019 buttonPos pos = up ; 00020 int bcounter = 0 ; 00021 while (true) { 00022 switch (pos) { 00023 case up : 00024 if (!b1.read()) { // now down 00025 pressEvent = 1 ; // transition occurred 00026 pos = down ; 00027 } 00028 break ; 00029 case down : 00030 if (b1 == 1) { // no longer down 00031 bcounter = 3 ; // wait four cycles 00032 pos = bounce ; 00033 } 00034 break ; 00035 case bounce : 00036 if (b1 == 0) { // down again - button has bounced 00037 pos = down ; // no event 00038 } else if (bcounter == 0) { 00039 pos = up ; // delay passed - reset to up 00040 } else { 00041 bcounter-- ; // continue waiting 00042 } 00043 break ; 00044 } 00045 wait(0.03); 00046 } 00047 } 00048 00049 /* ---- Main function (default thread) ---- 00050 Note that if this thread completes, nothing else works 00051 */ 00052 int main() { 00053 led = 1 ; // Initially off 00054 pollT.start(callback(polling)); 00055 00056 int counter = 2; 00057 int rate = 1; 00058 00059 00060 //functions with counter 00061 while(1){ 00062 if(pressEvent){ 00063 pressEvent = 0; 00064 rate = rate + 2; 00065 if(rate > 10){ 00066 rate = 1; 00067 } 00068 } 00069 00070 counter--; 00071 if(counter == 0){ 00072 led = !led; 00073 counter = rate; 00074 } 00075 00076 wait(0.1); 00077 } 00078 00079 // Functions 00080 float LED_SW = 0.2; 00081 00082 while(1){ 00083 if (pressEvent) { 00084 pressEvent = 0; 00085 LED_SW = LED_SW + 0.2; 00086 if (LED_SW > 1){ 00087 LED_SW = 0.2; 00088 } 00089 } 00090 00091 led = !led; 00092 wait(LED_SW); 00093 } 00094 00095 00096 00097 }
Generated on Mon Jul 18 2022 09:53:08 by
1.7.2