串口通信控制AT89C52单片机共阴极数码管和8个led灯代码
时间: 2023-08-30 14:04:10 浏览: 201
好的,以下是一个简单的串口通信控制AT89C52单片机共阴极数码管和8个LED灯的代码示例:
```
#include <reg52.h>
#include <intrins.h>
#define FOSC 11059200L
#define BAUD 9600
#define TIMER_1 (65536 - FOSC / 12 / BAUD)
sbit LATCH1 = P1^0; // 数码管锁存信号
sbit LATCH2 = P1^1;
sbit LATCH3 = P1^2;
sbit LATCH4 = P1^3;
sbit LED1 = P2^0; // LED灯控制信号
sbit LED2 = P2^1;
sbit LED3 = P2^2;
sbit LED4 = P2^3;
sbit LED5 = P2^4;
sbit LED6 = P2^5;
sbit LED7 = P2^6;
sbit LED8 = P2^7;
unsigned char code LED_CATHODE[] = { 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F }; // 数码管段码表,共阴极
unsigned char xdata LED_BUFF[4]; // 数码管缓存
void UartInit() // 串口初始化
{
TMOD |= 0x20; // 启用定时器1,模式2
TH1 = TIMER_1 / 256; // 计算波特率重载值
TL1 = TIMER_1 % 256;
TR1 = 1; // 启动定时器1
SCON = 0x50; // 启用串口,方式1,允许接收
ES = 1; // 使能串口中断
EA = 1; // 使能全局中断
}
void UartSend(unsigned char dat) // 发送一个字节
{
SBUF = dat;
while(!TI); // 等待发送完成
TI = 0;
}
void UartSendString(unsigned char *s) // 发送一个字符串
{
while(*s)
{
UartSend(*s++);
}
}
void Delay10ms() // 延时10毫秒
{
unsigned char i, j;
i = 10;
j = 145;
do
{
while (--j);
} while (--i);
}
void Display(unsigned char *buff) // 数码管显示函数
{
LATCH1 = 0;
P0 = LED_CATHODE[buff[0]];
LATCH1 = 1;
LATCH2 = 0;
P0 = LED_CATHODE[buff[1]];
LATCH2 = 1;
LATCH3 = 0;
P0 = LED_CATHODE[buff[2]];
LATCH3 = 1;
LATCH4 = 0;
P0 = LED_CATHODE[buff[3]];
LATCH4 = 1;
}
void Led(unsigned char led) // LED灯控制函数
{
LED1 = led & 0x01;
LED2 = led & 0x02;
LED3 = led & 0x04;
LED4 = led & 0x08;
LED5 = led & 0x10;
LED6 = led & 0x20;
LED7 = led & 0x40;
LED8 = led & 0x80;
}
void main()
{
unsigned char i, ch;
UartInit();
for(i = 0; i < 4; i++)
{
LED_BUFF[i] = 0;
}
while(1)
{
if(RI) // 接收到数据
{
ch = SBUF;
RI = 0;
switch(ch)
{
case '0':
LED_BUFF[0] = 0;
break;
case '1':
LED_BUFF[0] = 1;
break;
case '2':
LED_BUFF[0] = 2;
break;
case '3':
LED_BUFF[0] = 3;
break;
case '4':
LED_BUFF[0] = 4;
break;
case '5':
LED_BUFF[0] = 5;
break;
case '6':
LED_BUFF[0] = 6;
break;
case '7':
LED_BUFF[0] = 7;
break;
case '8':
LED_BUFF[0] = 8;
break;
case '9':
LED_BUFF[0] = 9;
break;
case 'a':
case 'A':
Led(0x01);
break;
case 'b':
case 'B':
Led(0x02);
break;
case 'c':
case 'C':
Led(0x04);
break;
case 'd':
case 'D':
Led(0x08);
break;
case 'e':
case 'E':
Led(0x10);
break;
case 'f':
case 'F':
Led(0x20);
break;
case 'g':
case 'G':
Led(0x40);
break;
case 'h':
case 'H':
Led(0x80);
break;
default:
LED_BUFF[0] = 0;
Led(0x00);
break;
}
Display(LED_BUFF); // 显示数码管
}
Delay10ms();
}
}
void UartIsr() interrupt 4 using 1 // 串口中断服务函数
{
if(RI) // 接收到数据
{
RI = 0;
}
}
```
以上代码中,通过串口接收数据,根据数据的不同来控制数码管和LED灯的显示。其中,使用了定时器1和中断来实现串口通信。在串口中断服务函数中,通过判断RI寄存器的值来确定是否接收到了数据。
阅读全文