目录
配置串口
这里我们主要是配置:串行控制寄存器SCON和波特率选择特殊功能寄存器。
SBUF是串口数据缓存寄存器,我们接发的数据就存在这里。
SCON
1.B7,B6主要就是确定串行口的工作方式,我们一般是使用模式1,也就是B7=0,B6=1.
下图是不同模式的配置要求
2.B5在方式2和方式3是配置为1,其余为0。
3.B4:想让单片机接收数据就置一,反之置零。
4.B3,B4在方式2和方式3是配置为1,其余为0.
5.B1,B0初始化配置为0.
SBUF
PCON
1.B7一般置0,置1波特率加倍。
2.B6一般不用不需要配置。
串口模式图
从上图我们知道我们配置完串口后,还需要重新配置下定时器。
定时器
我们一般使用定时器1并且将M1和M0配置成1,0.
串口向电脑发送数据
main.c
#include <REGX52.H>
#include "Delay.h"
#include "UART.h"
unsigned char Sec;
void main()
{
UartInit();
while(1)
{
UART_SendByte(Sec);//发送一个字节
Sec++;
Delay(1000);//延时防止误差
}
}
Delay.c&Delay.h
//Delay.c
void Delay(unsigned int xms)
{
unsigned char i, j;
while(xms--)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
}
}
//Delay.h
#ifndef __DELAY_H__
#define __DELAY_H__
void Delay(unsigned int xms);
#endif
UART.c&UART.h
//UART.c
#include <REGX52.H>
/**
* @brief 串口初始化
* @param 无
* @retval 无
*/
void UartInit(void) //4800bps@12.000MHz
{
PCON |= 0x80; //使能波特率倍速位SMOD
SCON = 0x50; //8位数据,可变波特率
TMOD &= 0x0F; //设置定时器模式
TMOD |= 0x20; //设置定时器模式
TL1 = 0xF3; //设置定时初始值
TH1 = 0xF3; //设置定时重载值
ET1 = 0; //禁止定时器%d中断
TR1 = 1; //定时器1开始计时
}
/**
* @brief 串口发送
* @param Byte
* @retval 无
*/
void UART_SendByte(unsigned char Byte)
{
SBUF = Byte;//TX发送
while(TI==0);//发送到了数据TI==1
TI=0;//软件复位
}
//UART.h
#ifndef __UART_H__
#define __UART_H__
void UartInit(void);
void UART_SendByte(unsigned char Byte);
#endif
电脑通过串口控制LED灯&将接受的数据发送到电脑上
接收需要我们额外设置下中断
main.c
#include <REGX52.H>
#include "Delay.h"
#include "UART.h"
void main()
{
UartInit();
while(1)
{
}
}
void UART_Routine() interrupt 4
{
if(RI==1)//如果接受标志位为1,接受了数据
{
P2 = SBUF;//接受数据
UART_SendByte(SBUF);//将接收的数据发送到电脑串口
RI = 0;//接受标志位清0,软件复位
}
}
Delay.c&Delay.h
//Delay.c
void Delay(unsigned int xms)
{
unsigned char i, j;
while(xms--)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
}
}
//Delay.h
#ifndef __DELAY_H__
#define __DELAY_H__
void Delay(unsigned int xms);
#endif
UART.c&UART.h
//UART.c
#include <REGX52.H>
/**
* @brief 串口初始化
* @param 无
* @retval 无
*/
void UartInit(void) //4800bps@12.000MHz
{
PCON |= 0x80; //使能波特率倍速位SMOD
SCON = 0x50; //8位数据,可变波特率
TMOD &= 0x0F; //设置定时器模式
TMOD |= 0x20; //设置定时器模式
TL1 = 0xF3; //设置定时初始值
TH1 = 0xF3; //设置定时重载值
ET1 = 0; //禁止定时器%d中断
TR1 = 1; //定时器1开始计时
ES = 1;
EA = 1;
}
/**
* @brief 串口发送
* @param Byte
* @retval 无
*/
void UART_SendByte(unsigned char Byte)
{
SBUF = Byte;
while(TI==0);
TI=0;
}
//UART.h
#ifndef __UART_H__
#define __UART_H__
void UartInit(void);
void UART_SendByte(unsigned char Byte);
#endif