一、初识串口
二、串口编程示例
/*
串口波特率9600
每隔一秒,单片机向PC发送一个字符串
PC上位机串口调试助手发送字母o点亮LED,发送字母c关闭LED
*/
#include "reg52.h"
#include <intrins.h>
#include <string.h>
#define SIZE 12
sbit D5 = P3^7;
sfr AUXR = 0X8E;
char cmd[12];
void Delay1000ms() //@11.0592MHz
{
unsigned char i, j, k;
_nop_();
i = 8;
j = 1;
k = 243;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void UartInit(void) //9600bps@11.0592MHz
{
AUXR = 0x01;
SCON = 0x50;//配置串口工作方式1,REN使能接收
TMOD &= 0x0F;
TMOD |= 0x20;//配置定时器1工作方式为8位自动重装
TH1 = 0xFD;
TL1 = 0xFD;//9600波特率初值
TR1 = 1; //启动定时器1
EA = 1;//开启总中断
ES = 1;//开启串口中断
}
void sendByte(char data_msg)
{
SBUF = data_msg;
while(!TI);
TI = 0;
}
void sendString(char *str)
{
while(*str != '\0'){
sendByte(*str);
str++;
}
}
void main()
{
D5 = 1;
//配置C51串口通信方式
UartInit();
while(1){
Delay1000ms();
//向发送缓冲区写入数据,就完成数据的发送
sendString("hello world\r\n");
//怎么知道收到数据?若RI=1(收到数据后由硬件置1)
}
}
void Uart_Handler() interrupt 4
{
static int i = 0;//静态变量,只被初始化一次
if(RI){//中断处理函数中,对于接收中断的响应
RI = 0;//清除接收中断标志位
cmd[i] = SBUF;
i++;
if(i == SIZE){
i = 0;
}
if(strstr(cmd,"en")){
D5 = 0;
i = 0;
memset(cmd,'\0',SIZE);
}
if(strstr(cmd,"se")){
D5 = 1;
i = 0;
memset(cmd,'\0',SIZE);
}
}
if(TI);
}