lab 2 part 1
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 //int noofcycles = 1 ; 00017 //int waittime = 0.1 ; 00018 00019 int waittime [5] = { 2,4,6,8,10 }; 00020 enum buttonPos { up, down, bounce }; // Button positions 00021 void polling() { 00022 buttonPos pos = up ; 00023 int bcounter = 0 ; 00024 while (true) { 00025 switch (pos) { 00026 case up : 00027 if (!b1.read()) { // now down 00028 pressEvent = 1 ; // transition occurred 00029 pos = down ; 00030 } 00031 break ; 00032 case down : 00033 if (b1 == 1) { // no longer down 00034 bcounter = 3 ; // wait four cycles 00035 pos = bounce ; 00036 } 00037 break ; 00038 case bounce : 00039 if (b1 == 0) { // down again - button has bounced 00040 pos = down ; // no event 00041 } else if (bcounter == 0) { 00042 pos = up ; // delay passed - reset to up 00043 } else { 00044 bcounter-- ; // continue waiting 00045 } 00046 break ; 00047 } 00048 wait(0.03); 00049 } 00050 } 00051 00052 /* ---- Main function (default thread) ---- 00053 Note that if this thread completes, nothing else works 00054 */ 00055 int main() { 00056 led = 1 ; // Initially off 00057 pollT.start(callback(polling)); 00058 int i = 0 ; 00059 int count = waittime[i]; 00060 while(true) { 00061 wait(0.1); 00062 if (pressEvent) { 00063 pressEvent = 0 ; // clear the event variable 00064 i = (i+1)%5; 00065 count = waittime[i]; 00066 } 00067 else{ 00068 if(count!=0){ 00069 count-- ; 00070 } 00071 else if(count == 0){ 00072 led = !led ; 00073 count = waittime[i]; 00074 } 00075 } 00076 00077 } 00078 }
Generated on Thu Aug 11 2022 19:23:57 by
1.7.2