这是我前几天无聊自己写的交通灯程序,在51单片机上实现的。基本的定时的交通灯转换是实现了,根据时间来改变交通灯的变换。可以下载下来看看的,电路图和原程序都有,代码就自己下载吧。我不全放上了。
仿真原理图如下(proteus仿真工程文件可到本帖附件中下载)
单片机源程序:
- #include<reg51.h>
- sbit beiR=P1^0;
- sbit beiY=P1^1;
- sbit beiG=P1^2;
- sbit nanR=P1^3;
- sbit nanY=P1^4;
- sbit nanG=P1^5;
- uint a,b,c,type,j,i;
- void Delay(uint x) //延时
- {
- uchar i;
- while(x--)for(i=0;i<120;i++);
- }
- void delay_ms(uint q) //延时
- {
- uint i,j;
- for(i=q;i>0;i--)
- for(j=141;j>0;j--);
- }
- void shumaguan(uint k) //数码管显示
- {
- b=k/10;
- c=k%10;
- P3=11111101;
- P2=smg_dw[b];//选段码
- delay_ms(20);//延时5ms
- P3=11111110;
- P2=smg_dw[c];//选段码
- delay_ms(20);//延时5ms
- }
- main()
- {
- TMOD=0x01; //设置定时器T0为工作方式1定时
- TH0=(65536-50000)/256;
- TL0=(65536-50000)%256;
- TR0=1; //启动T0计数
- ET0=1; //允许T0中断
- EX0=1; //允许外部中断0中断
- EA=1; //开中断
- IT0=1; //允许外部中断0为边沿触发方式
- a=10; //倒计时10s
- type=1;
- while(1){
- switch(type)
- {
- case 1: //东西向绿灯与南北向红灯亮
- beiR=0;beiY=1;beiG=1;
- nanR=1;nanY=1;nanG=0;
- shumaguan(a);
- break;
- case 2: //东西向黄灯闪烁,绿灯关闭
- if(a%2!=0)
- {
- beiR=1;beiY=0;beiG=1;
- }
- if(a%2==0)
- {
- beiR=1;beiY=1;beiG=1;
- }
- shumaguan(a);
- break;
- case 3: //东西向红灯,南北向绿灯亮
- beiR=1;beiY=1;beiG=0;
- nanR=0;nanY=1;nanG=1;
- shumaguan(a);
- break;
- case 4: //南北向黄灯闪烁3次
- if(a%2!=0)
- {
- nanR=1;nanY=0;nanG=1;
- }
- if(a%2==0)
- {
- nanR=1;nanY=1;nanG=1;
- }
- shumaguan(a);
- break;
- }
- }
- }
复制代码
全部资料51hei下载地址:
51单片机实现定时交通灯.rar
(55.81 KB, 下载次数: 568)
|