STM32标准库开发——串口发送/单字节接收

USART基本结构

串口发送信息

启动串口一的时钟

c 复制代码
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);

初始化对应串口一的时钟,引脚,将TX引脚设置为复用推挽输出。

c 复制代码
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);

配置串口一配置寄存器,设置波特率为9600,关闭硬件流控,不使用校验位,数据长度为八字节

c 复制代码
USART_InitTypeDef  USART_InitStruct;
USART_InitStruct.USART_BaudRate=9600;
USART_InitStruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode=USART_Mode_Tx;
USART_InitStruct.USART_Parity=USART_Parity_No;
USART_InitStruct.USART_StopBits=USART_StopBits_1;
USART_InitStruct.USART_WordLength=USART_WordLength_8b;
USART_Init(USART1,&USART_InitStruct);

封装串口发送字节函数

c 复制代码
void Serial_SendByte(uint8_t Byte)
{
	USART_SendData(USART1,Byte);
	while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)== RESET);	
}

封装串口发送字符串函数

c 复制代码
void Serial_SendString(char *String)
{
	uint8_t i;
	for (i=0;String[i]!='\0';i++)
	{
		Serial_SendByte(String[i]);
	}
}

封装串口发送数组函数

c 复制代码
void Serial_SendArray(uint8_t *Array,uint16_t Length)
{
	uint16_t i;
	for (i=0;i<Length;i++)
	{
		Serial_SendByte(Array[i]);
	}
}

封装串口发送数字函数

c 复制代码
uint32_t Serial_Pow(uint32_t x, uint32_t y)
{
	uint32_t Result = 1;
	while(y--)
	{
		Result *= x;
	}
	return Result;
}
void Serial_SendNumber(uint32_t Number, uint8_t Length)
{
	uint8_t i;
	for(i=0; i<Length; i++)
	{
		Serial_SendByte(Number / Serial_Pow(10,Length-i-1)%10);
	}
}

进阶一:重定向print输出到串口中

c 复制代码
/*
 fputc是print函数的底层所以,修改底层文件就能将print输出重定向到串口。
*/
int fputc(int ch, FILE  *f)
{
	Serial_SendByte(ch);
	return ch;
}

进阶二:封装Serial_Sprintf完成串口输出功能

c 复制代码
/*
char String[100];
sprintf(String,"Num=%d\r\n",666)
Serial_SendString(String);
等价于以下这行代码
printf("Num=%d\r\n",666)
*/
void Serial_Printf(char *format, ...)
{
	char String[100];
	va_list arg;
	va_start(arg,format);
	vsprintf(String,format,arg);
	va_end(arg);
	Serial_SendString(String);
}

注意:

①发送和接受均不需要手动清除发送或接收标志位,因为当发送字节或者读取字节内容时,硬件会自动清0

②Serial_Printf("串口输出也支持中文输出");

当编码格式为 UTF-8时才需要配置参数 --no-multibyte-chars

当编码格式为GB2312时则不需要配置参数

相关推荐
Freak嵌入式14 小时前
MCU 低功耗模式解析:时钟门控、电源门控、深度休眠
人工智能·python·单片机·嵌入式硬件·开源·依赖倒置原则·micropython
国科安芯14 小时前
FreeRTOS RISC-V 浮点上下文切换移植:在 IAR 工程中完整保存 FPU 寄存器
java·开发语言·单片机·嵌入式硬件·算法·系统架构·risc-v
躺不平的理查德15 小时前
STM32时钟树(Clock Tree)
stm32·单片机·嵌入式硬件
Javenwww16 小时前
STM32中DMA的使用——串口数据的DMA传输
单片机
qq_4017004116 小时前
经典的电压基准源电路
单片机·嵌入式硬件
茯苓gao17 小时前
嵌入式开发笔记:电机参数辨识与自学习完全指南——从电气参数到机械特性的深度解析
笔记·嵌入式硬件·学习
西安景驰电子17 小时前
PCIe 授时卡原理及应用
运维·服务器·windows·单片机·嵌入式硬件·fpga开发
派勤电子19 小时前
5G物联网网关工控主板选型指南(超小尺寸工业级嵌入式硬件解决方案)
嵌入式硬件·工业网关·工控主板·工控主板选型·嵌入式工控主板·5g物联网网关·超小尺寸工控主板
&Hello Code19 小时前
2.一套可落地的 STM32 六层架构:基础工程框架搭建
stm32·嵌入式硬件·架构
sramdram20 小时前
高速低功耗stt-mram工业级存储方案
嵌入式硬件·mram·stt-mram·低功耗stt-mram