Lab2 - Example 1
Fork of digitalInPolling_sample by
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 00003 // Labs 2: polling and rate change by button 00004 00005 DigitalIn b1(PTD0, PullUp); 00006 DigitalOut led(LED1); 00007 00008 double rate = 100; 00009 00010 Thread pollT ; // thread to poll 00011 volatile int pressEvent = 0 ; // Variabe set by the polling thread 00012 00013 enum buttonPos { up, down, bounce }; // Button positions 00014 void polling() { 00015 buttonPos pos = up ; 00016 int bcounter = 0 ; 00017 while (true) { 00018 switch (pos) { 00019 case up : 00020 if (!b1.read()) { // now down 00021 pressEvent = 1 ; // transition occurred 00022 pos = down ; 00023 } 00024 break ; 00025 case down : 00026 if (b1 == 1) { // no longer down 00027 bcounter = 3 ; // wait four cycles 00028 pos = bounce ; 00029 } 00030 break ; 00031 case bounce : 00032 if (b1 == 0) { // down again - button has bounced 00033 pos = down ; // no event 00034 } else if (bcounter == 0) { 00035 pos = up ; // delay passed - reset to up 00036 } else { 00037 bcounter-- ; // continue waiting 00038 } 00039 break ; 00040 } 00041 Thread::wait(30); 00042 } 00043 } 00044 00045 /* ---- Main function (default thread) ---- 00046 Note that if this thread completes, nothing else works 00047 */ 00048 int main() { 00049 led = 1 ; // Initially off 00050 int cycle = 1; // cycle of 100 waiting 00051 int changeCycle = 2; 00052 pollT.start(callback(polling)); 00053 00054 while(true) { 00055 if (pressEvent) { 00056 pressEvent = 0 ; // clear the event variable 00057 00058 switch (changeCycle) { 00059 case 2 : 00060 changeCycle = 4 ; 00061 break ; 00062 case 4 : 00063 changeCycle = 6 ; 00064 break ; 00065 case 6 : 00066 changeCycle = 8 ; 00067 break ; 00068 case 8 : 00069 changeCycle = 10 ; 00070 break ; 00071 case 10 : 00072 changeCycle = 2 ; 00073 break ; 00074 } 00075 cycle = 1; 00076 } 00077 00078 00079 if(cycle == changeCycle) { 00080 if(led == 1) { 00081 led = 0; 00082 } else if (led == 0) { 00083 led = 1; 00084 } 00085 00086 cycle = 1; // reset the cycle 00087 } else { 00088 cycle = cycle + 1; // go to the next cycle 00089 } 00090 00091 Thread::wait(100) ; 00092 } 00093 }
Generated on Mon Aug 8 2022 18:53:49 by
1.7.2
