基于51單片機的模擬交通燈
注:P1口連接至LED用于顯示紅綠燈,P0口接數(shù)碼管段碼,用于顯示時間;
兩個74HC573控制段碼和位碼。段碼接P20,位碼接P21
------------------------------------------------*/
#include
#define uchar unsigned char
#define uint unsigned int
sbit DUAN=P2^0;
sbit WEI=P2^1;
/*------------------------------------------------
全局變量
------------------------------------------------*/
bit red,green,yellow,turnred;//定義紅綠黃燈標志位
code unsigned char tab[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,
0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x00} ;
//共陰數(shù)碼管0-9
uchar shi,ge;
/*------------------------------------------------
------------------------------------------------*/
void delay(uint t)
{
while(t--);
}
/*------------------------------------------------
主程序
------------------------------------------------*/
main()
{
TMOD |=0x01;
TH0=(65535-50000)/256;
TL0=(65535-50000)%256;
EA=1;//開中斷
ET0=1;
TR0=1;//開定時器
P1=0xfc;//紅燈亮
red =1;
while(1)
{
WEI=1;
P0=0xfe;
WEI=0;
DUAN=1;
P0=shi;//顯示十位
DUAN=0;
delay(300);
WEI=1;
P0=0xfd;
WEI=0;
DUAN=1;
P0=ge;//顯示十位
DUAN=0;
delay(300);
}
}
/*------------------------------------------------
定時器0中斷函數(shù)
------------------------------------------------*/
void tim(void) interrupt 1
{
static uchar second=60,count;
TH0=(65535-50000)/256;
TL0=(65535-50000)%256;
count++;
if (count==20)
{
count=0;
second--;//秒減1
if(second==0)
{
if(red)
{
red=0;yellow=1;
second=5;
P1=0xF3;//黃燈亮5秒
}
else if(yellow && !turnred)
{
yellow=0;green=1;
second=50;
P1=0xCF;//綠燈亮50秒
}
else if(green)
{
yellow=1;green=0;
second=5;
P1=0xF3;//黃燈亮5秒
turnred=1;
}
else if(yellow && turnred)
{
red=1;yellow=0;
P1=0xFC;//紅燈亮60秒
second=60;
turnred=0;
}
}
shi=tab[second/10];
ge=tab[second%10];
}
}
評論