较Version1.1, 此处通过string.h文件中的strcmp()函数简化了对简单命令的判断.
#include <STC89C5xRC.H>
#include <string.h>
unsigned char code DIG_CODE[10] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};//对应数码管显示0~9
char buf[30];
int tcount = 0;//记录经过的10ms区间段个数
int sec = 15;//倒计时初始值记录
int sec2 = 0;//倒计时初始值
void T0_INT() interrupt 1 //timer0中断, 每10ms触发一次
{
TR0 = 0;//关闭timer0
TH0 = 0xD8;
TL0 = 0xF0;//65536 - 10000 = 55536
if(tcount % 2 == 0)
{
//显示个位数
P2 = 0;// P2 = 0 -> (P24, P23, P22) = (0, 0, 0) -> 右数第一个数字点亮
P0 = DIG_CODE[sec2 % 10];
tcount ++;
}
else if(tcount % 2 == 1)
{
//显示十位数
P2 = 1 << 2;//P2 = 0000 0100 -> (P24, P23, P22) = (0, 0, 1) -> 右数第二个数字点亮
P0 = DIG_CODE[sec2 / 10];
tcount ++;
}
if(tcount == 100) //10ms * 100 = 1000ms = 1s -> 1s时间到
{
tcount = 0;
sec2 --;
if(sec2 == -1)
{
sec2 = sec;
}
}
TR0 = 1;//重新开启timer0
}
int main()
{
int i = 0;
TMOD = 0x21;
SCON = 0x50;//设置串行通信格式
TH0 = 0xD8;
TL0 = 0xF0;//65536 - 10000 = 55536
IE = 0x82;//EA + ET0 -> 1000 0010
TH1 = 0xE6;
TL1 = 0xE6;//1200bps under 12MHz
RI = 0;
TR0 = 0;//暂不开启timer0
TR1 = 1;//开启timer1
while(1)
{
if(RI == 1)//收到数据
{
RI = 0;
buf[i ++] = SBUF;//接收串口发来的数据
buf[i] = '\0';//手动添加字符串结束标志
if(i == 29)//防止数组访问越界
{
i = 0;
}
if(buf[i - 1] == 'E')//到达结尾
{
i = 0;
if(strcmp(buf, "Start.E") == 0)//Start.命令
{
TR0 = 1;//启动timer0 -> 开启倒计时器
}
else if(strcmp(buf, "Stop.E") == 0)
{
TR0 = 0;//关闭timer0 -> 暂停倒计时器
}
else if(buf[0] == 'S' && buf[1] == 'e' && buf[2] == 't' && buf[3] == ' ' &&
buf[4] == 'i' && buf[5] == 'n' && buf[6] == 'i' && buf[7] == 't' &&
buf[8] == ' ' && buf[9] == 'v' && buf[10] == 'a' && buf[11] == 'l' &&
buf[12] == 'u' && buf[13] == 'e' && buf[14] == ' ' && buf[15] == 'a' && buf[16] == 's' && buf[17] == ' ' && buf[20] == '.')
{
sec = (buf[18] - 48) * 10 + (buf[19] - 48);
}
}
}
}
return 0;
}