程序启动后计时初值为15, 之后可通过串口发来的数据(如"99")来修改下一次计时初值.
#include <STC89C5xRC.H>
unsigned char code DIG_CODE[10] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};//对应数码管显示0~9
char buf[2];
int tcount = 0;//记录经过的10ms区间段个数
int sec = 15;//倒计时初始值记录
int sec2 = 15;//倒计时初始值
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 = 1;//开启timer0
TR1 = 1;//开启timer1
while(1)
{
if(RI == 1)
{
RI = 0;
buf[i++] = SBUF;//接收串口发来的数据
if(i == 2)
{
i = 0;
sec = (buf[0] - 48) * 10 + (buf[1] - 48);
}
}
}
return 0;
}