51单片机-串口-串口发送显示
1. 视频
bilibili视频地址:
https://www.bilibili.com/video/av92932152
51单片机-串口-串口发送显示
2. 文件
文件下载链接:
https://download.csdn.net/download/weixin_43130546/12203484
3. 串口
PCON电源管理寄存器
SCON串口控制寄存器
模式&波特率(宋雪松P183)
SCON主要用模式1,的波特率
对应的,要用定时器T1&T2的模式2
TH1 = TL1 = 256 - 晶振值/12/2/16/波特率
(256是TL1的溢出值,12指12个时钟周期,16是硬件因素)
SBUF
两个SBUF寄存器,分别负责接收和发送缓冲
4. 串口配置代码
EA = 1;
void ConfigUART(unsigned long baud)
{
TH1 = 256 - (11059200 / 12 / 32) / baud;
TL1 = TH1;
SCON = 0x50;
TMOD &= 0x0F;
TMOD |= 0x20;
ET1 = 0;
ES = 1;
TF1 = 0;
TR1 = 1;
}
void InterruptUART(void) interrupt 4
{
if(RI)
{
RI = 0;
UARTNum = SBUF;
SBUF = UARTNum;
}
if(TI)
{
TI = 0;
}
}
5. 例程代码
串口助手发送0xXX,在单片机数码管上以十进制&十六进制显示
#include <reg52.h>
sbit DULA = P2^6;
sbit WELA = P2^7;
unsigned char code DUTable[16] =
{
0x3F,0x06,0x5B,0x4F,
0x66,0x6D,0x7D,0x07,
0x7F,0x6F,0x77,0x7C,
0x39,0x5E,0x79,0x71
};
unsigned char code WETable[8] =
{
~0x80,~0x40,~0x20,~0x10,
~0x08,~0x04,~0x02,~0x01
};
unsigned char LedBuff[8] =
{
0x3F,0x3F,0x3F,0X40,
0X3F,0X3F,0X08,0X3F
};
unsigned char T0RH,T0RL;
unsigned char UARTNum;
void ConfigTimer0(unsigned char ms);
void ConfigUART(unsigned long band);
void ShowNum(unsigned char num);
void main(void)
{
EA = 1;
ConfigTimer0(1);
ConfigUART(9600);
while(1)
{
ShowNum(UARTNum);
}
}
void ConfigTimer0(unsigned char ms)
{
unsigned long tmp;
tmp = 11059200 / 12;
tmp = tmp * ms / 1000;
tmp = 65536 - tmp;
tmp += 12;
T0RH = (unsigned char)(tmp>>8);
T0RL = (unsigned char)tmp;
TH0 = T0RH;
TL0 = T0RL;
TMOD &= 0xF0;
TMOD |= 0x01;
ET0 = 1;
TF0 = 0;
TR0 = 1;
}
void ConfigUART(unsigned long baud)
{
TH1 = 256 - (11059200 / 12 / 32) / baud;
TL1 = TH1;
SCON = 0x50;
TMOD &= 0x0F;
TMOD |= 0x20;
ET1 = 0;
ES = 1;
TF1 = 0;
TR1 = 1;
}
void ShowNum(unsigned char num)
{
LedBuff[0] = DUTable[num/1%10];
LedBuff[1] = DUTable[num/10%10];
LedBuff[2] = DUTable[num/100%10];
LedBuff[3] = 0x40;
LedBuff[4] = DUTable[num & 0x0F];
LedBuff[5] = DUTable[num >> 4];
LedBuff[6] = 0x08;
LedBuff[7] = 0x3F;
}
void LedScan(void)
{
static unsigned char i = 0;
P0 = 0x00;
DULA = 1;
DULA = 0;
P0 = WETable[i];
WELA = 1;
WELA = 0;
P0 = LedBuff[i];
DULA = 1;
DULA = 0;
i++;
i &= ~0xF8;
}
void InterruptTimer0(void) interrupt 1
{
TH0 = T0RH;
TL0 = T0RL;
LedScan();
}
void InterruptUART(void) interrupt 4
{
if(RI)
{
RI = 0;
UARTNum = SBUF;
SBUF = UARTNum;
}
if(TI)
{
TI = 0;
}
}
来源:CSDN
作者:hello_StarLee
链接:https://blog.csdn.net/weixin_43130546/article/details/104596570