|
#include <reg52.h>
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
unsigned char code LedChar[] = { //數碼管顯示字符轉換表
0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
};
unsigned char LedBuff[7] = { //數碼管+獨立LED顯示緩沖區
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
bit flag1s = 1; //1秒定時標志
unsigned char T0RH = 0; //T0重載值的高字節
unsigned char T0RL = 0; //T0重載值的低字節
void ConfigTimer0(unsigned int ms);
void TrafficLight();
void main()
{
EA = 1; //開總中斷
ENLED = 0; //使能數碼管和LED
ADDR3 = 1;
ConfigTimer0(1); //配置T0定時1ms
while (1)
{
if (flag1s) //每秒執行一次交通燈刷新
{
flag1s = 0;
TrafficLight();
}
}
}
/* 配置并啟動T0,ms-T0定時時間 */
void ConfigTimer0(unsigned int ms)
{
unsigned long tmp; //臨時變量
tmp = 11059200 / 12; //定時器計數頻率
tmp = (tmp * ms) / 1000; //計算所需的計數值
tmp = 65536 - tmp; //計算定時器重載值
tmp = tmp + 13; //補償中斷響應延時造成的誤差
T0RH = (unsigned char)(tmp>>8); //定時器重載值拆分為高低字節
T0RL = (unsigned char)tmp;
TMOD &= 0xF0; //清零T0的控制位
TMOD |= 0x01; //配置T0為模式1
TH0 = T0RH; //加載T0重載值
TL0 = T0RL;
ET0 = 1; //使能T0中斷
TR0 = 1; //啟動T0
}
/* 交通燈顯示刷新函數 */
void TrafficLight()
{
static unsigned char color = 2; //顏色索引:0-綠色/1-黃色/2-紅色
static unsigned char timer = 0; //倒計時定時器
if (timer == 0) //倒計時到0時,切換交通燈
{
switch (color) //LED8/9代表綠燈,LED5/6代表黃燈,LED2/3代表紅燈
{
case 0: //切換到黃色,亮3秒
color = 1;
timer = 2;
LedBuff[6] = 0xE7;
break;
case 1: //切換到紅色,亮30秒
color = 2;
timer = 29;
LedBuff[6] = 0xFC;
break;
case 2: //切換到綠色,亮40秒
color = 0;
timer = 39;
LedBuff[6] = 0x3F;
break;
default:
break;
}
}
else //倒計時未到0時,遞減其計數值
{
timer--;
}
LedBuff[0] = LedChar[timer%10]; //倒計時數值個位顯示
LedBuff[1] = LedChar[timer/10]; //倒計時數值十位顯示
}
/* LED動態掃描刷新函數,需在定時中斷中調用 */
void LedScan()
{
static unsigned char i = 0;
P0 = 0xFF;
P1 = (P1 & 0xF8) | i;
P0 = LedBuff[i];
if (i < 6)
i++;
else
i = 0;
}
/* T0中斷服務函數,完成LED掃描和秒定時 */
void InterruptTimer0() interrupt 1
{
static unsigned int tmr1s = 0;
TH0 = T0RH;
TL0 = T0RL;
LedScan();
tmr1s++;
if (tmr1s >= 1000)
{
tmr1s = 0;
flag1s = 1;
}
}
|
|