基于51单片机的简易交通灯

新手上路,望大佬们指点!

LED9,LED8表示红灯(29s);LED6,LED5表示黄灯(2s);LED3,LED2表示绿灯(39s);

代码如下:

#include <REG52.H>

sbit ADDR3 = P1^3;
sbit ENLED = P1^4;

unsigned char code LedChar[] = {
    0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
    0xB0, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
};
unsigned char LedBuff[7] = {
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
bit flagls = 1 ; //1Ã붨ʱ±êÖ¾
unsigned char T0RH = 0;
unsigned char T0RL = 0;

void ConfigTimer0(unsigned int ms);
void TrafficLight();

void main()
{
    EA = 1;
    ENLED = 0;
    ADDR3 = 1;
    ConfigTimer0(1);   //ÅäÖÃT0¶¨Ê±1ms
    
    while(1)
    {
        if(flagls)
        {
            flagls = 0;
            TrafficLight();
        }
    }
}

void ConfigTimer0(unsigned int ms)
{
    unsigned long tmp;
    
    tmp = 11052900/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(0 == timer)
    {
        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;
    P1 = (P1 & 0xF8) | i;
    P0 = LedBuff[i];
    if(i < 6)
        i++;
    else
        i = 0;
}

void InterruptTimer0() interrupt 1
{
    static unsigned int tmrls = 0; 
    
    TH0 = T0RH;
    TL0 = T0RL;
    LedScan();
    tmrls++;
    if(tmrls >= 1000)
    {
        tmrls = 0;
        flagls = 1;
    }
}

  • 15
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值