目的:设计一个十字路口的交通灯控制系统,四组灯(红黄绿)对应十字路口的四个方向,用两位的数码管显示剩余的时间。
1、打开keil5软件,新建工程 2、芯片选择“AT89C51”,点击“OK”进入下一步3、新建程序文件,输入代码 代码如下
#include "reg51.h" sbit hr=P1^0; sbit hy=P1^1; sbit hg=P1^2; sbit sr=P1^3; sbit sy=P1^4; sbit sg=P1^5; sbit h1=P2^0; sbit h2=P2^1; sbit s1=P2^2; sbit s2=P2^3; int count=0; int time=0; int num[10]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90}; void delay(int t) { int x,y; for(x=0;x<t;x++) { for(y=0;y<100;y++); } } void main() { P1=0xff; hg=0;sr=0;P2=0x00; TMOD=0x01; TL0=0x3C;TH0=0xB0; ET0=1;EA=1;TR0=1; while(1) { if(time<30) { h1=1;P0=num[((30-time)/10)];delay(10);h1=0; h2=1;P0=num[((30-time)%10)];delay(10);h2=0; s1=1;P0=num[((33-time)/10)];delay(10);s1=0; s2=1;P0=num[((33-time)%10)];delay(10);s2=0; } else if(time<33) { h1=1;P0=num[((33-time)/10)];delay(10);h1=0; h2=1;P0=num[((33-time)%10)];delay(10);h2=0; s1=1;P0=num[((33-time)/10)];delay(10);s1=0; s2=1;P0=num[((33-time)%10)];delay(10);s2=0; } else if(time<63) { h1=1;P0=num[((66-time)/10)];delay(10);h1=0; h2=1;P0=num[((66-time)%10)];delay(10);h2=0; s1=1;P0=num[((63-time)/10)];delay(10);s1=0; s2=1;P0=num[((63-time)%10)];delay(10);s2=0; } else if(time<66) { h1=1;P0=num[((66-time)/10)];delay(10);h1=0; h2=1;P0=num[((66-time)%10)];delay(10);h2=0; s1=1;P0=num[((66-time)/10)];delay(10);s1=0; s2=1;P0=num[((66-time)%10)];delay(10);s2=0; } } } void timer() interrupt 1 { TH0=0x3C; TL0=0xB0; count=count+1; if(count==20) { count=0; time=time+1; if(time==30) { P1=0xff;hy=0;sr=0; } else if(time==33) { P1=0xff;hr=0;sg=0; } else if(time==63) { P1=0xff;hr=0;sy=0; } else if(time==66) { time=0; P1=0xff;hg=0;sr=0; } } }4、设置参数,选中“Output”,勾选“Creat HEX File”,点击“OK”退出界面(为了生成.hex文件) 5、编译程序 6、生成.hex文件
(1)、点击“File”,选择新建工程(2)、选择保存路径并命名 (3)、依次作如下设置
至此,工程建立完成。
(1)、选择所需元件并连接好电路图 (点击P添加电路元件)
(2)、双击51单片机,点击下图红框处,添加步骤1中的.hex文件到单片机 (3)、运行电路,进行仿真测试,仿真结果如下