这两天学习了交通灯的相关知识并把程序码了出来,包含的知识有定时器,中断,led灯的刷新,数码管显示倒计时等知识,在写程序时因为一个函数名打错了,耽误了不少时间,这也是以后码程序的时候需要注意的。在下对这个交通灯比较感兴趣,所以购买了一套交通灯的元件准备研究一下,同时现在还在看"定时炸dan"的程序。
下面是交通灯程序
#include<reg52.h>
sbit ENLED = P1^1;
sbit ADDR0 = P2^0;
sbit ADDR1 = P2^1;
sbit ADDR2 = P2^2;
unsigned char code LedChar[] = {
0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
};
unsigned char LedBuff[7] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
};
bit flag1s = 1;
unsigned char T0RH = 0;
unsigned char T0RL = 0;
void ConfigTimer0(unsigned int ms);
void TrafficLight();
void main()
{
EA = 1;
ENLED = 0;
ConfigTimer0(1);
while(1)
{
if(flag1s == 1)
{
flag1s = 0;
TrafficLight();
}
}
}
void ConfigTimer0(unsigned int ms)
{
unsigned long tmp;
tmp = 32768000/12;
tmp = (tmp*ms)/1000;
tmp = 65536 - tmp;
tmp = tmp + 13;
T0RH = (unsigned char)(tmp>>8);
T0RL = (unsigned char)tmp;
TMOD &= 0xF0;
TMOD |= 0x01;
TH0 = T0RH;
TL0 = T0RL;
ET0 = 1;
TR0 = 1;
}
void TrafficLight()
{
static unsigned char color = 2;
static unsigned char timer = 0;
if(timer ==0)
{
switch(color)
{
case 0:
color = 1;
timer = 2;
LedBuff[6] = 0xE7;
break;
case 1:
color = 2;
timer = 29;
LedBuff[6] = 0xFC;
break;
case 2:
color = 0;
timer = 39;
LedBuff[6] = 0x3F;
break;
default:
break;
}
}
else
{
timer--;
}
LedBuff[0] = LedChar[timer%10];
LedBuff[1] = LedChar[timer/10];
}
void LedScan()
{
static unsigned char i = 0;
P0 = 0xFF;
switch(i)
{
case 0:ADDR2 = 0;ADDR1 = 0;ADDR0 = 0;i++0 = LedBuff[5];break;
case 1:ADDR2 = 0;ADDR1 = 0;ADDR0 = 1;i++0 = LedBuff[4];break;
case 2:ADDR2 = 0;ADDR1 = 1;ADDR0 = 0;i++0 = LedBuff[3];break;
case 3:ADDR2 = 0;ADDR1 = 1;ADDR0 = 1;i++0 = LedBuff[2];break;
case 4:ADDR2 = 1;ADDR1 = 0;ADDR0 = 0;i++0 = LedBuff[1];break;
case 5:ADDR2 = 1;ADDR1 = 0;ADDR0 = 1;i++0 = LedBuff[0];break;
case 6:ADDR2 = 1;ADDR1 = 1;ADDR0 = 0;i = 00 = LedBuff[6];break;
default: break;
}
}
void InterruptTimer0() interrupt 1
{
static unsigned int tmr1s = 0;
TH0 = T0RH;
TL0 = T0RL;
LedScan();
tmr1s++;
if(tmr1s>=1000)
{
tmr1s = 0;
flag1s = 1;
}
}
|