小弟手头有这么个需求:
读取串口送来的输入,根据输入的各个字节,进行状态机的跳转。
用Perl写的状态机代码demo如下,目前遇到的问题是:
代码运行到while(1)就陷入进去、出不来,
while(1){}之后的$din赋值,状态机根本吃不到,
所以实际上状态机卡死在INIT,动弹不得。
不知怎么样能让状态机在顺序输入的激励下、逐个状态跳转,
求指点,thx~!
use strict ;
use warnings ;
# input to the state machine
my $din ;
# FSM's state table.
# Expected input sequence is:
# AA 99 00 01 ....
# In which:
# "AA" and "99" are two bytes of header,
# "00" and "01" are two bytes of uart ID.
my %next_state = (
"INIT" => sub{
# If receives "AA" from input,
# then jumpt to "HEADER0" state:
$din eq "AA" and return "HEADER0" ;
# Otherwise just stay here:
return "INIT" ;
},
"HEADER0" => sub{
# If receives "99" from input,
# then proceed to "HEADER1" state:
$din eq "99" and return "HEADER1" ;
# Otherwise, return to initial state:
return "INIT" ;
},
"HEADER1" => sub{
# Capture first byte of uart ID:
return "UARTID0";
},
"UARTID0" => sub{
# Capture second byte of uart ID:
return "UARTID1";
},
"FINISHED" => sub{
return "INIT";
},
);
# Set state machine's initial state.
my $cur_state = "INIT" ;
# Integer for debugging purpose.
my $itgi = 0;
# Run the state machine.
while(1){
$cur_state = $next_state{$cur_state}();
print "$itgi, will jump to: $cur_state\n\n";
$itgi++;
}
# Send in input bytes:
$din = "AA" ;
sleep(1) ;
$din = "99" ;
sleep(1) ;
--
FROM 117.64.249.*