Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
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 // Sharing a global variable between two threads is not safe in general 00017 // but it can be ok if a) update is atomic and b) only one thread writes 00018 00019 enum buttonPos { up, down, bounce }; // Button positions 00020 void polling() { 00021 buttonPos pos = up ; 00022 int bcounter = 0 ; 00023 00024 while (true) { 00025 ThisThread::sleep_for(30) ; // poll every 30ms 00026 switch (pos) { 00027 case up : 00028 if (!b1.read()) { // now down 00029 pressEvent = 1 ; // transition occurred 00030 pos = down ; 00031 } 00032 break ; 00033 case down : 00034 if (b1 == 1) { // no longer down 00035 bcounter = 3 ; // wait four cycles 00036 pos = bounce ; 00037 } 00038 break ; 00039 case bounce : 00040 if (b1 == 0) { // down again - button has bounced 00041 pos = down ; // no event 00042 } else if (bcounter == 0) { 00043 pos = up ; // delay passed - reset to up 00044 } else { 00045 bcounter-- ; // continue waiting 00046 } 00047 break ; 00048 } 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 //int time [4] = {200,400,600,800,1000 }; 00058 pollT.start(callback(polling)); 00059 int rate=200; 00060 while(true) { 00061 //if (pressEvent) { 00062 00063 led = !led ; 00064 00065 //} 00066 if(pressEvent) { 00067 rate += 200; 00068 pressEvent = 0 ; // clear the event variable 00069 } 00070 if (rate>1000){ 00071 rate=200; 00072 } 00073 00074 ThisThread::sleep_for(rate) ; // delay for 100ms 00075 } 00076 }
Generated on Fri Aug 5 2022 06:31:54 by
1.7.2