- #include<reg51.H>
- #define uchar unsigned char
- #define uint unsigned int
- uchar code table[]={ //共陰極數碼管碼表
- 0x3f,0x06,0x5b,0x4f,
- 0x66,0x6d,0x7d,0x07,
- 0x7f,0x6f,0x77,0x7c,
- 0x39,0x5e,0x79,0x71,
- 0xC9,0xFF,0x40};//設置碼,測試碼,不計時碼
- void delay(uint x);//延時函數
- void display(uchar,uchar,uchar,uchar); //數碼管顯示函數
- void mkeys(); //鍵盤函數
- void traffic(); //交通燈函數
- uchar num,num1,num2, //1南北 2東西
- shi1,ge1,shi2,ge2,
- value1,value2,//南北 綠燈時間 黃燈時間
- value3,value4,//東西 綠燈時間 黃燈時間
- count1,count2,flag1,flag2; //南北標記 東西標記
- void main()
- {
- TMOD=0x01;
- TH0=(65536-45872)/256;
- TL0=(65536-45872)%256;
- EA=1; //中斷的總開關
- ET0=1; //定時器0的專用中斷開關
- TR0=1; //啟動定時器開始定時計數的開關
- /*初狀態*/
- value1=15; //南北 黃綠燈默認值
- value2=5;
- value3=10; //東西 黃綠燈默認值
- value4=5;
- num1=value1; //南北數碼管先綠燈時間
- num2=value2+value1;//東西紅燈時間
- shi1=num1/10;
- ge1=num1%10;
- shi2=num2/10;
- ge2=num2%10;
- P1=0x41;//初始狀態:東西紅燈 南北綠燈 20s 15s
- while(1){
- if(num==20) //定時器1s
- {
- num=0;
- num1--;
- num2--;
- traffic();
- shi1=num1/10;
- ge1=num1%10;
- shi2=num2/10;
- ge2=num2%10;
- }
- {
- mkeys();
- }
- display(shi1,ge1,shi2,ge2);
- }
- }
- void traffic() //紅綠燈主控制程序
- {
- if(num1==0){
- count1++;
- if(count1==1){
- P1=0x42; //東西紅燈 南北黃燈 5s 5s
- num1=value2;
- }
- if(count1==2){
- num1=value3+value4;//東西綠燈 南北紅燈 10s 15s
- P1=0x14;
- }
- if(count1==3){
- P1=0x41;// 東西黃燈 南北紅燈 5s 5s
- num1=value4;
- count1=0;
- }
- }
- if(num2==0){
- count2++;
- if(count2==1){
- //P1=0x14;//東西綠燈 南北紅燈
- num2=value3;
- }
- if(count2==2){
- P1=0x24;//東西黃燈 南北紅燈
- num2=value4;
- }
- if(count2==3){
- num2=value1+value2; //東西紅燈 南北綠燈
- num1=value1;
- count2=0;
- }
-
- }
- }
- void display(uchar shi1,uchar ge1,uchar shi2,uchar ge2) //數碼管顯示子函數
- {
- uchar temp;
- temp=P2;
- P2=0xfe; //位選
- P0=table[shi1]; //段選
- delay(5);
-
- P2=0xfd;
- P0=table[ge1];
- delay(5);
-
- P2=0xfb;
- P0=table[shi2];
- delay(5);
-
- P2=0xf7;
- P0=table[ge2];
- delay(5);
- }
- void delay(uint x)//延時子函數
- {
- uint i,j;
- for(i=x;i>0;i--)
- for(j=110;j>0;j--);
- }
復制代碼 |