利用51单片机,结合下面两段代码,实现数码管显示信号灯时间: 第一段: #include<reg52.h> #define uchar unsigned char uchar count,ge,shi,tt,time,color,flag; uchar table[]={0xFC,0x60,0xDA,0xF2,0x66,0xB6,0xBE,0xE0, 0xFE,0xF6,0xEE,0x3E,0x9C,0x7A,0x9E,0x8E}; void yellow() { time=3; P1=0x08; if(flag==1) color=3; if(flag==0) color=2; } void red() { time=20; P1=0x10; flag=1; color=1; } void green() { time=20; P1=0x04; flag=0; color=1; } void light() { switch(color){ case 1: yellow();break; case 2: red();break; case 3: green();break; } } void main(){ color=2; flag=0; count=3; time=10; tt=0; TMOD=0x01; TL0=0xB7; TH0=0x3C; EA=1; ET0=1; TR0=1; while(1){ if(tt==20){ if(count<=0){ light(); count=time; } tt=0; TR0=0; count--; TR0=1; } } } void time_0() interrupt 1{ TL0=0xB7; TH0=0x3C; tt++; } 第二段: #include <reg51.h> unsigned char code table[] = {0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE0, 0xFE, 0xF6, 0xEE, 0x3E, 0x9C, 0x7A, 0x9E, 0x8E}; unsigned char i, j, flag; char Count; void putch(unsigned char n) { SBUF=n; while(TI==0); TI=0; } void main() { TMOD=0X01; EA=1; ET0=1; TH0=(65536-50000)/256; TL0=(65536-50000)%256; TR0=1; flag=0; Count=59; while(1) { i=table[Count/10]; j=table[Count%10]; putch(i); putch(j); } } void Timer0() interrupt 1 { flag++; TH0=(65536-50000)/256; TL0=(65536-50000)%256; if(flag==20){ flag=0; Count=Count-1; } if(Count<0){ Count=59; } i=table[Count/10]; j=table[Count%10]; putch(i); putch(j); }
时间: 2023-10-16 11:06:21 浏览: 140
51单片机数码管显示时钟
根据您提供的两段代码,我已经帮您进行了整合,可以实现数码管显示信号灯时间的功能。请参考下面代码:
```c
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar count, ge, shi, tt, time, color, flag;
uchar table[] = {0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE0, 0xFE, 0xF6, 0xEE, 0x3E, 0x9C, 0x7A, 0x9E, 0x8E};
void yellow() {
time = 3;
P1 = 0x08;
if (flag == 1)
color = 3;
if (flag == 0)
color = 2;
}
void red() {
time = 20;
P1 = 0x10;
flag = 1;
color = 1;
}
void green() {
time = 20;
P1 = 0x04;
flag = 0;
color = 1;
}
void light() {
switch (color) {
case 1:
yellow();
break;
case 2:
red();
break;
case 3:
green();
break;
}
}
void putch(uchar n) {
SBUF = n;
while (TI == 0);
TI = 0;
}
void main() {
color = 2;
flag = 0;
count = 3;
time = 10;
tt = 0;
TMOD = 0x11;
TH1 = 0xFD;
TL1 = 0xFD;
TH0 = 0xB7;
TL0 = 0x3C;
EA = 1;
ET0 = 1;
ES = 1;
TR0 = 1;
TR1 = 1;
while (1) {
if (tt == 20) {
if (count <= 0) {
light();
count = time;
}
tt = 0;
TR0 = 0;
count--;
TR0 = 1;
}
}
}
void time_0() interrupt 1 {
TL0 = 0xB7;
TH0 = 0x3C;
tt++;
}
void Timer1() interrupt 3 {
putch(0x7F);
if (flag == 1) {
putch(0x40);
} else if (color == 1) {
putch(0x40);
} else {
putch(0x00);
}
}
```
代码实现的思路是,在定时器0中断中控制信号灯的颜色和时间,利用定时器1和串口通信实现数码管的显示。其中,定时器0中断控制信号灯的颜色和时间,定时器1中断用于驱动数码管的显示,串口通信用于向数码管发送显示信息。
需要注意的是,由于使用了串口通信,需要在程序中添加波特率设置,代码中使用的是9600波特率。同时,需要在数码管显示芯片的OE引脚接一个普通IO口,并在定时器1中断中输出0x7F,以控制OE引脚的高低电平,从而实现数码管的显示。
希望能够对您有所帮助!
阅读全文