用于对数字计数器建模的有限状态机



我必须使用Arduino C中的enumswitch/case属性编码创建一个有限状态机(FSM)来创建数字计数器。我应该有 16 个状态:0-7 计数和 7-0 倒计时。每当用户单击键盘上的键时,计数就会反转。例如,它应该打印(0,1,2,3,4,5,6,7,0,1,2,3,4,...),然后在按下一个键后,打印(4,3,2,1,0,7,6,5...)等。我完全被困住了,需要一些帮助。谢谢!

我有一个代码的一般骨架:

enum State {
0;
1;
2;
// 16 of these...
}
void setup() {
Serial.begin(9600);
Serial.println("FSM Forwards & Backwards");
}
void loop() {
state = nextState(state);
switch (state) {
case 0:
// more states(cases) here
// create a FSM to determine the next state of the machine.
}
State nextState(State state){
char input = Serial.read();
// more states(cases) here
}
bool checkReverse(){
// which reverses the direction of the counter if a key on the 
keyboard has been pressed
}

对我来说似乎是家庭作业。 Arduino使用布线语言,这实际上是C++。它包含了很多不同的图书馆思想。

你可能想要这样的东西,请注意,它的内部状态由变量状态和方向组成。它将每秒更新自动机的状态。同时,它将扫描传入数据中的"r"字符并反转方向。

struct FSM {
enum state_t {
step0,
step1,
...
step8,
step9,
...
};
state_t state;
bool direction;
FSM() {state = step0;}
void nextState(bool toggle) {
state_t oldState = state;
state_t ret;
if(direction) {
switch(oldState) {
case step0:
ret = step8;
break;
case step1:
ret = step8;
break;
...
}
else {
case step0:
ret = step1;
break;
case step1:
ret = step2;
break;
...
}
state = ret; // Update state
direction = toggle ? !direction: direction; // Update toggle
}
int getOutput() {
switch(state) {
case step0:
return 0;
...
case 8:
return 7;
case 9:
return 6;
...
};
FSM fsm;
bool toggle = false;
unsigned intlastTime;
void setup() {
lastTime = millis();
}
void loop() {
int c = Serial.read();
if(c == 'r') toggle = ! toggle;
bool timeToCount = false;
if(lastTime + 1000 < millis()) { // Every second
timeToCount = true;
lastTime = millis();
fsm.nextState(toggle); // 
Serial.println(fsm.getOutput());
toggle = false;
}

}

最新更新