我被看过状态机,我看到了Arduino,我只是想知道有没有一种方法可以调整下面的代码以使其以c程序运行,而不是让它在Arduino上运行?并从用户输入中读取传感器。
#define SENSORS PINB // define the ATmega328 Port to read the switches
#define LIGHTS PORTD // define the ATmega328 Port to drive the lights
// Linked data structure
struct State {
int Out;
int Time;
int Next[4];};
typedef const struct State STyp;
#define goS 0
#define waitS 1
#define goW 2
#define waitW 3
STyp FSM[4]={
{0x21,3000,{goS,waitS,goS,waitS}}, //State 0 (goS) go South.
{0x22, 500,{goW,goW,goW,goW}}, //State 1 (waitS) wait South.
{0x0C,3000,{goW,goW,waitW,waitW}}, //State 2 (goW) go West.
{0x14, 500,{goS,goS,goS,goS}}}; //State 3 (waitW) wait West.
int State; // index to the current state
int Input;
void setup(){
DDRB &= B11111100; // Port B pins 0 and 1 as inputs (Arduino pins 8 and 9)
DDRD |= B11111100; // Port D pins 2 to 7 as outputs (Arduino pins 2 to 7)
}
void loop(){
LIGHTS = (FSM[State].Out)<<2; // set lights
delay(FSM[State].Time);
Input = SENSORS & B00000011; // read sensors
State = FSM[State].Next[Input];
}
setup()
和loop()
您可以使用此简单的main()
模仿Arduino环境的行为:
int main(void) {
setup();
for (;;) {
loop();
}
}
您必须为DDRB
之类的端口寄存器提供仿真。在最简单的情况下,您可以定义一个将被写入的变量:
int DDRB;
其他端口寄存器需要更多工作。
顺便说一句,为什么不使用pinMode()
或digitalWrite()
之类的标准功能?这会使您的生活变得更加轻松。
最后,您需要提供自己的函数版本,例如delay()
。