1、确定一共有多少种状态,这里的状态有开和关,细分还有say thankyou 和警告
2、确定状态之间的迁移条件
如果按照四种状态:开、关、说谢谢、警告,那么这四种状态之前的迁移条件很明显了
分两个函数:
1、检查是否需要迁移状态;
2、迁移状态.
遍历各种状态检查是否有状态需要发生迁移.一般用一个switch将各种状态列出,然后在各种状态里面用if检查是否需要迁移状态,如果需要迁移,做好标记.
再次遍历各种状态,检查哪些状态做了标记,迁移到新状态,并做相应的操作,比如进入关的时候,做关门动作。
典型的状态机结构:
enum { state_A, state_B, state_C } state = state_A
while(1)
{
switch ( state )
{
case state_A:
if ( event_A )// 这里也可以用switch
{
action_1() // 在某状态下发生某事件执行某个动作,并转入下个状态
state = state_B
}
else if ( event_B )
{
}
else
{
}
break
case state_B:
... ...
}
}
#include <STC12C52.H>
#define uchar unsigned char
#define uint unsigned int
sbit key=P1^2
sbit p1_6=P1^6
void delay(uchar delay_time)
{
uchar n
uint m
for (n=0n<delay_timen++)
{
for(m=0m<10000m++)
}
}
void keyscan()
{
if(key==0)
{
delay(5)
if(key==0)
while(!key)
{
p1_6 = 0
delay(20)
p1_6 = 1
delay(20)
}
}
}
void main()
{
WDT_CONTR = 0x3C
while(1)
{
keyscan()
WDT_CONTR = 0x3C
}
}
这个功能可以用中断来实现,当然,现在我写的这个也可以实现。由于你用的晶振频率不知道,所以你自己修改一下延时时间,再把头文件改一下,就可以了,我试验了,可以实现改功能。