新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計應(yīng)用 > 51單片機用C語言實現(xiàn)交通燈

51單片機用C語言實現(xiàn)交通燈

作者: 時間:2016-11-25 來源:網(wǎng)絡(luò) 收藏
51單片機C語言實現(xiàn)交通燈(紅綠燈)源程序
交通燈,紅黃綠燈交替亮,怎樣實現(xiàn)呢?其實就是根據(jù)單片機定時器及倒計時的程序修改。

源程序如下:



#include

bit red,green,yellow,turnred; //定義紅、黃、綠及轉(zhuǎn)紅標(biāo)志

code unsigned char tab[]=
{0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
//共陰數(shù)碼管 0-9

unsigned char Dis_Shiwei;//定義十位
unsigned char Dis_Gewei; //定義個位
void delay(unsigned int cnt) //用于動態(tài)掃描數(shù)碼管的延時程序
{
while(--cnt);
}

main()
{

TMOD |=0x01;//定時器設(shè)置 10ms in 12M crystal定時器0,工作方式1,16位定時器
TH0=0xd8; //65535-10000=55535=D8F0(十六進制)
TL0=0xf0;
IE= 0x82; //中斷控制,EA=1開總中斷,ET0=1:定時器0中斷允許
TR0=1; //開定時器0中斷

P1=0xfc;//紅燈亮,根據(jù)紅黃綠接燈的順序。
red =1;
while(1)
{
P0=Dis_Shiwei;//顯示十位,這里實現(xiàn)用8位數(shù)碼管,即左1位
P2=0;
delay(300);//短暫延時
P0=Dis_Gewei; //顯示個位,左數(shù),2位
P2=1;
delay(300);
}

}



void tim(void) interrupt 1 using 1
{
static unsigned char second=60,count; //初值60

TH0=0xd8;//重新賦值,10毫秒定時
TL0=0xf0;
count++;
if (count==100)
{
count=0;
second--;//秒減1
if(second==0)
{ //這里添加定時到0的代碼 ,可以是燈電路,繼電器吸合等,或者執(zhí)行一個程序
if(red) //紅滅,先轉(zhuǎn)黃
{
red=0;yellow=1;
second=4;
P1=0xF3;//黃燈亮4秒,黃燈為過渡燈,再根據(jù)情況轉(zhuǎn)綠或轉(zhuǎn)紅
}
else if(yellow && !turnred)
{
yellow=0;green=1;
second=25;
P1=0xCF;//綠燈亮25秒,
}
else if(green)
{
yellow=1;green=0;
second=4;
P1=0xF3;//黃燈亮4秒
turnred=1;
}
else if(yellow && turnred) //綠燈滅,轉(zhuǎn)黃燈,后紅燈,turnred=1時
{
red=1;yellow=0;
P1=0xFC;//紅燈亮60秒
second=60;
turnred=0; //接下來是轉(zhuǎn)黃,綠。
}

}
Dis_Shiwei=tab[second/10];//十位顯示值處理
Dis_Gewei=tab[second]; //個位顯示處理

}
}


關(guān)鍵詞: 51單片機C語言交通

評論


技術(shù)專區(qū)

關(guān)閉