有关状态机可以参考:
用状态机原理进行软件设计.pdf
Practical.Statecharts.in.CCQuantum.Programming.for.Embedded.Systems.pdf
/*
* (网络搜索有关状态机的东西,找到一个题目,简单做一下)
* 假设地铁的门有2个状态,开和关。
* 在关的情况下,投入一个硬币,门就开了;
* 在关的状态下,强行进入,就发出警告。
* 在开的情况下,人一进入,门就关了;
* 在开的情况下,继续投币,就说:“thank you”。
* 要求用C代码写出状态机,并写出main函数,完全写出代码实现这个状态机。
*
*/
#include
typedef enum
{
STATION_CLOSE,
STATION_OPEN,
}StationState;
struct station_door
{
unsigned int doorstate;
};
struct station_door g_door;
void station_init(void)
{
g_door.doorstate = STATION_CLOSE;
}
/*投币处理函数*/
unsigned int EventHandlerOfPutCoin()
{
switch(g_door.doorstate)
{
case STATION_CLOSE:
g_door.doorstate = STATION_OPEN;
printf("the door is open\n");
break;
case STATION_OPEN:
printf("thank you\n");
break;
default :
break;
}
return 0;
}
/*进入处理函数*/
unsigned int EventHandlerOfGetIn()
{
switch(g_door.doorstate)
{
case STATION_CLOSE:
printf("alerting\n");
break;
case STATION_OPEN:
g_door.doorstate = STATION_CLOSE;
printf("the door is close\n");
break;
default :
break;
}
return 0;
}
void get_event(int *event)
{
if(NULL == event)
return;
if(g_door.doorstate == STATION_CLOSE)
{
printf("Current door state is CLOSE\n");
}
else
{
printf("Current door state is OPEN\n");
}
printf("Please select event\n");
printf("1:put coin\n");
printf("2:get in\n");
scanf("%d",event);
}
void event_handler(int event)
{
if(event == 1)
{
EventHandlerOfPutCoin();
}
else if(event == 2)
{
EventHandlerOfGetIn();
}
else
{
return;
}
}
int main(void)
{
int event;
station_init();
while(1)
{
get_event(&event);
event_handler(event);
}
return 0;
}
阅读(2463) | 评论(0) | 转发(0) |