12_串口通信

发布时间 2023-11-19 13:53:20作者: 爱吃冰激凌的黄某某

串口通信

串口介绍

image-20231109173147287

接口及引脚定义

image-20231109173843709

硬件电路

image-20231109174104169

电平标准

image-20231109174338867

常见通信接口比较

image-20231109175520844

相关术语

image-20231109180050130

51单片机的UART

image-20231109180721754

串口参数及时序图

image-20231109180811515

串口模式图

image-20231110154334107

串口和中断系统

image-20231110154922440

串口相关寄存器

image-20231110160412990

单片机每隔一秒向电脑发送数据

UART.c

#include <REGX52.H>

/**
  * @brief 串口初始化
  * @param 无
  * @retval 无
  */
void UART_Init()		//4800bps@11.0592MHz
{
	PCON |= 0x80;		//使能波特率倍速位SMOD
	SCON = 0x40;		//8位数据,可变波特率
	TMOD &= 0x0F;		//设置定时器模式
	TMOD |= 0x20;		//设置定时器模式
	TL1 = 0xF4;			//设置定时初始值
	TH1 = 0xF4;			//设置定时重载值
	ET1 = 0;			//禁止定时器中断
	TR1 = 1;			//定时器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 UART_Init();
void UART_SendByte(unsigned char Byte);

#endif

main.c

#include <REGX52.H>
#include "Delay.h"
#include "UART.h"

unsigned char Sec;

void main()
{
	UART_Init();
	
	while(1)
	{
		UART_SendByte(Sec++);
		Delay(1000);
	}
}

Delay.c

void Delay(unsigned int xms)	//@12.000MHz
{
	unsigned char data 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

运行效果

stc-isp-v6.92E_ABmkvwSJ4F

使用发送数据控制LED

UART.c

#include <REGX52.H>

/**
  * @brief 串口初始化
  * @param 无
  * @retval 无
  */
void UART_Init()		//4800bps@11.0592MHz
{
	PCON |= 0x80;		//使能波特率倍速位SMOD
	SCON = 0x50;		//8位数据,可变波特率
	TMOD &= 0x0F;		//设置定时器模式
	TMOD |= 0x20;		//设置定时器模式
	TL1 = 0xF4;			//设置定时初始值
	TH1 = 0xF4;			//设置定时重载值
	ET1 = 0;			//禁止定时器中断
	TR1 = 1;			//定时器1开始计时
	EA=1;				//CPU开放中断
	ES=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 UART_Init();
void UART_SendByte(unsigned char Byte);

#endif

ChangeLED.c

#include <REGX52.H>

void ChangeLED()
{
	bit t;
	t=P2_0;
	P2_0=P2_7;
	P2_7=t;
	t=P2_1;
	P2_1=P2_6;
	P2_6=t;
	t=P2_2;
	P2_2=P2_5;
	P2_5=t;
	t=P2_3;
	P2_3=P2_4;
	P2_4=t;
}

ChangeLED.h

#ifndef __CHANGELED_H__
#define __CHANGELED_H__

void ChangeLED();

#endif

main.c

#include <REGX52.H>
#include "Delay.h"
#include "UART.h"
#include "ChangeLED.h"

void main()
{
	UART_Init();
	while(1)
	{
		
	}
}

void UART_Routine() interrupt 4
{
	if(RI==1)
	{
		P2=~SBUF;
		ChangeLED();
		UART_SendByte(SBUF);
		RI=0;
	}
}

运行效果

image-20231110175301662

image-20231110175349935

数据显示模式

image-20231110175954229

image-20231110180623766