C51仿真实现交通灯+单片机代码
http://www.51hei.com/bbs/dpj-141185-1.html
(出处: 单片机论坛)
在上一篇贴中,我们用了两个锁存器实现了交通灯的仿真,但是我们仔细观察,可以发现交通灯的闪烁规律还可以更细一步,使用4个锁存器就使代码变得很简洁了
仿真原理图如下(proteus仿真工程文件可到本帖附件中下载)
单片机源程序如下:
- #include<reg51.h>
- #include<intrins.h>
- #define uchar unsigned char
- #define uint unsigned int
- uchar m,n,k,f=1;
- uchar time1[]={20,120};//数码管第一状态5s,第二状态6s
- uchar time2[]={100,10,60};//交通灯第一状态5s,第二状态3s,第三状态3s
- uint index1=1;
- uint index2=0;
- uchar code table[]={
- 0x3f,0x06,0x5b,0x4f,
- 0x66,0x6d,0x7d,0x07,
- 0x7f,0x6f,0x77,0x7c,
- 0x39,0x5e,0x79,0x71,
- 0x00
- };
- uchar P2_0=0x01;//(P2.0~P2.3)选择数码管
- uchar P3_0=0x01;//(P30~P33)选择交通灯
- uchar P1_0=0x04;//控制灯状态
- int number=6;
- void showNumber()
- {
- if(index1==0)
- {
- P2=P2_0;
- P0=~table[number];
- if(number==0)
- {
- P2=0x00;
- P2_0<<=1;
- if(P2_0==0x10)
- P2_0=0x01;
- number=6;
- index1=1;
- }
- }
- }
- void openLight()
- {
- switch(index2)
- {
- case 0:
- if(m==time2[index2])
- {
- index2=1;
- m=0;
- }
- break;
- case 1:
- if(m==time2[index2])
- {
- P1_0=P1_0^0x04;
- k++;
- m=0;
- if(k==8)
- {
- index2=2;
- P1_0=0x02;
- k=0;
- }
-
- }
- break;
- case 2:
- if(m==time2[index2])
- {
- P1_0=0x04;
- index2=0;
- P3_0=P3_0<<1;
- if(P3_0==0x10)
- P3_0=0x01;
- m=0;
- }
- break;
- }
- P1=0x00;
- P3=0xff;
- P1=0x01;
- P3=0x00;
- P1=0x00;
- P3=P3_0;
- P1=P1_0;
- P3=0x00;
- }
- void main()
- {
- P1=0x00;
- EA=1;//打开全局中断允许
- TMOD=0x11;//设置定时器工作方式
- TH0=15535/256;//计时50ms
- TL0=15535%256;
- TH1=15535/256;
- TL1=15535%256;
- ET0=1;//打开计时器中断允许
- ET1=1;
- TR0=1;//启动定时器
- TR1=1;
- while(1)
- { //openLight();
- showNumber();
- }
- }
- void ET_T0() interrupt 1
- {
- TH0=15535/256;
- TL0=15535%256;
- m++;
- openLight();
- }
- void ET_T1() interrupt 3
- {
- TH1=15535/256;
- TL1=15535%256;
- n++;
- switch(index1)
- {
- case 0:
- if(n==time1[index1])
- {
- number=(number-1)%6;
- n=0;
- }
- break;
- case 1:
- if(n==time1[index1])
- {
- index1=0;
- n=0;
- }
- break;
- }
- }
复制代码
所有资料51hei提供下载:
交通灯改进版.zip
(24.56 KB, 下载次数: 14)
|