專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計(jì)實(shí)例 >> 瀏覽文章

基于于51單片機(jī)的模擬交通燈

作者:我行天下   來源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時(shí)間:2014年03月30日   【字體:

/*-----------------------------------------------
  注:P1口連接至LED用于顯示紅綠燈,P0口接數(shù)碼管段碼,用于顯示時(shí)間;
兩個(gè)74HC573控制段碼和位碼。段碼接P20,位碼接P21
------------------------------------------------*/
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit DUAN=P2^0;  
sbit WEI=P2^1;
/*------------------------------------------------
                 全局變量
------------------------------------------------*/
bit red,green,yellow,turnred;//定義紅綠黃燈標(biāo)志位
 
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;//開定時(shí)器
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);
  }
}
/*------------------------------------------------
             定時(shí)器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];
  
    }
}

關(guān)閉窗口

相關(guān)文章