网友“西安-老赵”在定时中断中用状态机的办法实现18B20驱动程序
西安-老赵:18B20我在时间中断中用状态机的办法实现程序
木丁西—黄冈:
请问什么是状态机?
西安-老赵:
计数器就是个状态机,数字电路分为组合电路和时序电路.状态机就是时序电路.
下面是我的程序节选。
interrupt 12 void TPM2CH0_ISR(void){
TPM2C0SC_CH0F=0;
//PTDD_PTDD7=~PTDD_PTDD7;
if(tcount!=0) tcount--;
if(otcount1!=0) otcount1--;
if(otcount2!=0) otcount2--;
if(blitcount!=0) blitcount--;
else PTBD_PTBD6=1;
switch(onewireflag){
caseONEWIREFLAG0: onewire_reset_ts1ts2(); //onewire reset
onewireflag= ONEWIREFLAG1;
break;
caseONEWIREFLAG1: PTFDD_PTFDD2=0; //presence delay
PTFDD_PTFDD3=0;
PTFD_PTFD2=1;
PTFD_PTFD3=1;
onewireflag= ONEWIREFLAG2;
break;
case ONEWIREFLAG2:
write_byte_ts1(0xcc); // skip rom
write_byte_ts2(0xcc);
onewireflag= ONEWIREFLAG3;
break;
caseONEWIREFLAG3: write_byte_ts1(0x44); // Start Conversion
write_byte_ts2(0x44);
tmcount=90;
onewireflag= ONEWIREFLAG4;
break;
caseONEWIREFLAG4: tmcount--;
if (tmcount==0) //wait 4500ms for conversion complete
onewireflag= ONEWIREFLAG5;
break;
caseONEWIREFLAG5: onewire_reset_ts1ts2(); //onewire reset
onewireflag= ONEWIREFLAG6;
break;
caseONEWIREFLAG6: PTFDD_PTFDD2=0; //presence delay
PTFDD_PTFDD3=0;
PTFD_PTFD2=1;
PTFD_PTFD3=1;
onewireflag= ONEWIREFLAG7;
break;
caseONEWIREFLAG7:
write_byte_ts1(0xcc); // skip rom
write_byte_ts2(0xcc);
onewireflag= ONEWIREFLAG8;
break;
caseONEWIREFLAG8: write_byte_ts1(0xbe);
write_byte_ts2(0xbe); //Read Scratch Pad
onewireflag= ONEWIREFLAG9;
break;
caseONEWIREFLAG9: tmlobyte1=read_byte_ts1();//read temperaturelow byte
tmlobyte2=read_byte_ts2();
onewireflag= ONEWIREFLAG10;
break;
caseONEWIREFLAG10:tmhibyte1=read_byte_ts1();//read temperaturehigh byte
tmhibyte2=read_byte_ts2();
// databuffer=tmlobyte1|(tmhibyte1<<8);
databuffer=tmhibyte1;
databuffer=tmlobyte1;
// databuffer=tmlobyte2|(tmhibyte2<<8);
databuffer=tmhibyte2;
databuffer=tmlobyte2;
PTDD_PTDD7=~PTDD_PTDD7;
onewireflag= ONEWIREFLAG0;
break;
default:
break;
}
switch(keyhit){
case 0: if(PTDD_PTDD4==0)
keyhit=1;
break;
case 1:if(PTDD_PTDD4==0)
keyhit=2;
elsekeyhit=0;
break;
case 2:
if(PTDD_PTDD4==0)
keyvalue1=5;
keyhit=3;
case 3: if(PTDD_PTDD4==1){
keyhit=0;
keyvalue=keyvalue1;
blitcount=200;
PTBD_PTBD6=0;
}
default:
break;
}
}
西安-老赵:
延时用定时器,不死等,定时器时标到了,判断状态要不要翻转。
鸿哥--深圳:
这个状态机写得很好,一步一步切换非常好。有时候,也可以根据条件,直接从第1步切换到第3步或者第8步,不一定要切换到第2步,这个就是状态机的灵魂精华。
页:
[1]