串口
原理图
工作方式 1
配置串口:
- 工作方式 1,8 位 UART,波特率可变;
- 使用独立波特率作为串口的波特率发生器;
- 允许串口发送或接收数据完成之后请求中断;
- 直接将串口接收到的数据发送出去。
main.c 文件:
#include <reg51.h>
#ifndef SYSTEM_CLOCK
#define SYSTEM_CLOCK (1000000 * 12)
#endif
#define PCON_SMOD 0x80
#define PCON_SMOD0 0x40
sfr AUXR = 0x8E;
#define AUXR_BRTR 0x10
#define AUXR_BRTx12 0x04
#define AUXR_S1BRS 0x01
sfr BRT = 0x9C;
sfr AUXR1 = 0xA2;
#define AUXR1_UART_P1 0x80
#define UART1_BAUD_RATE 9600
void main() {
PCON &= ~PCON_SMOD;
PCON &= ~PCON_SMOD0;
SM0 = 0;
SM1 = 1;
REN = 1;
TI = 0;
RI = 0;
if((PCON & PCON_SMOD) == PCON_SMOD) {
BRT = 256 - (SYSTEM_CLOCK / 16 / 9600);
} else {
BRT = 256 - (SYSTEM_CLOCK / 32 / 9600);
}
AUXR |= AUXR_S1BRS;
AUXR |= AUXR_BRTx12;
AUXR |= AUXR_BRTR;
ES = 1;
EA = 1;
while(1) {}
}
void uartInterruptService() interrupt 4 {
unsigned char buffer = 0x00;
if (RI) {
RI = 0;
buffer = SBUF;
SBUF = buffer;
}
if (TI) {
TI = 0;
}
}
将编译好的 HEX 文件下载到单片机中,打开串口助手发送数据,可以看到单片机将数据回传:
|