-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateMachine.ino
89 lines (75 loc) · 1.83 KB
/
StateMachine.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <SoftTimers.h>
/**************************************************
* An hypothetical state machine needs to step from
* state to state. Each state has its own maximum
* duration:
* State #1 - IDLE (1000 ms)
* State #2 - LISTENING (200 ms)
* State #3 - SYNCHRONIZING (500 ms)
* State #4 - UPDATING (300 ms)
* State #1 ...
**************************************************/
SoftTimer nextStateTimer; //millisecond timer
const int STATE_IDLE = 0;
const int STATE_LISTENING = 1;
const int STATE_SYNCHRONIZING = 2;
const int STATE_UPDATING = 3;
int state = STATE_IDLE;
void setup() {
Serial.begin(115200);
//update timers
nextStateTimer.setTimeOutTime(1000); // IDLE, 1 second.
//start counting now
nextStateTimer.reset();
}
void loop() {
//show current state
switch(state)
{
case STATE_IDLE:
Serial.println("IDLE");
break;
case STATE_LISTENING:
Serial.println("LISTENING");
break;
case STATE_SYNCHRONIZING:
Serial.println("SYNCHRONIZING");
break;
case STATE_UPDATING:
Serial.println("UPDATING");
break;
default:
Serial.println("UNKNOWN STATE!");
break;
};
//look for next state...
if (nextStateTimer.hasTimedOut())
{
state++;
//limit state to known states
state = state%(STATE_UPDATING+1);
//reconfugure time based on new state
switch(state)
{
case STATE_IDLE:
nextStateTimer.setTimeOutTime(1000);
break;
case STATE_LISTENING:
nextStateTimer.setTimeOutTime(200);
break;
case STATE_SYNCHRONIZING:
nextStateTimer.setTimeOutTime(500);
break;
case STATE_UPDATING:
nextStateTimer.setTimeOutTime(300);
break;
default:
Serial.println("UNKNOWN STATE!");
break;
};
//start counting now
nextStateTimer.reset();
}
//hypothetical work...
//processState()
}