Example solution of rapid polling (with C++)
Fork of Task330_polling by
Revision 1:e84a51c98d75, committed 2017-10-23
- Comitter:
- noutram
- Date:
- Mon Oct 23 09:47:16 2017 +0000
- Parent:
- 0:397b84c74d17
- Child:
- 2:4cf6f5cba257
- Commit message:
- Tidy up and reduce latency
Changed in this revision
| SWPoll.hpp | Show annotated file Show diff for this revision Revisions of this file |
| main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/SWPoll.hpp Mon Oct 23 09:37:46 2017 +0000
+++ b/SWPoll.hpp Mon Oct 23 09:47:16 2017 +0000
@@ -3,23 +3,27 @@
class SWPoll {
private:
enum State {LOW, LOW_DEBOUNCE, HIGH, HIGH_DEBOUNCE};
- State state;
- DigitalIn& sw;
- DigitalOut& led;
- Timer t;
+ State state; // Internal state
+ DigitalIn& sw; // These are references (aliases) and MUST be initialised
+ DigitalOut& led; // ""
+ Timer t; // Each instance has it's own timer, so this is is finite
public:
+ //Constructor - MUST be given two parameters (for the switch and led) BY REFERENCE
SWPoll(DigitalIn& gpioIn, DigitalOut& gpioOut) : sw(gpioIn), led(gpioOut) {
state = LOW;
t.reset();
led = 0;
}
+ //Destructor - should the instance go out of scope, this is called
~SWPoll() {
//Shut down
t.stop();
t.reset();
led = 0;
}
+ //The public API - poll the switches
+ //Bascially, a mealy machine - uses a timer to manage switch bounce
void poll() {
switch (state)
{
@@ -42,8 +46,9 @@
case HIGH:
if (sw == 0) {
+ led = !led; //Toggle output on state transition
state = HIGH_DEBOUNCE;
- t.reset();
+ t.reset(); //(purely defensive)
t.start();
}
break;
@@ -52,7 +57,6 @@
state = LOW;
t.stop();
t.reset();
- led = !led; //Toggle output on state transition
}
break;
default:
--- a/main.cpp Mon Oct 23 09:37:46 2017 +0000
+++ b/main.cpp Mon Oct 23 09:47:16 2017 +0000
@@ -22,7 +22,7 @@
SWPoll switch1(sw1, red_led);
SWPoll switch2(sw2, green_led);
-
+//LOOK AT SWPoll.hpp for the definition of the SWPoll class
int main() {
@@ -45,38 +45,3 @@
}
-//Thread 1 - polling sw1 and controlling the red LED
-void task1()
-{
- //Loop forever
- while(1) {
- //Spin on sw1
- while (sw1 == RELEASED) {};
- //Allow short delay for switch bounce
- Thread::wait(200);
- //Spin again on sw1
- while (sw1 == PRESSED) {};
- //Toggle LED
- red_led = !red_led;
- //Again, wait for switch bounce
- Thread::wait(200);
- }
-}
-
-//Thread 2 - polling sw2 and controlling the green LED
-void task2()
-{
- //Loop forever
- while(1) {
- //Spin on sw2
- while (sw2 == RELEASED) {};
- //Allow short delay for switch bounce
- Thread::wait(200);
- //Spin again on sw2
- while (sw2 == PRESSED) {};
- //Toggle LED
- green_led = !green_led;
- //Again, wait for switch bounce
- Thread::wait(200);
- }
-}
