写一个STM32F103的串口驱动框架
以下是一个简单的STM32F103的串口驱动框架,包括初始化函数、发送函数、接收函数以及中断处理函数:
#include "stm32f10x.h"
void USART1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
// Enable clock for USART1, GPIOA, AFIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
// Configure USART1 pins: TX(PA9) and RX(PA10)
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// Configure USART1
USART_InitStruct.USART_BaudRate = 9600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStruct);
// Enable USART1 interrupt
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
// Enable USART1
USART_Cmd(USART1, ENABLE);
}
void USART1_SendChar(char ch)
{
while(!(USART1->SR & USART_SR_TXE));
USART1->DR = (uint16_t)ch;
}
void USART1_SendString(char* str)
{
while(*str)
{
USART1_SendChar(*str++);
}
}
char USART1_ReceiveChar(void)
{
while(!(USART1->SR & USART_SR_RXNE));
return (char)USART1->DR;
}
void USART1_IRQHandler(void)
{
if(USART1->SR & USART_SR_RXNE)
{
char ch = USART1_ReceiveChar();
// do something with received character
}
}
使用方法:
-
在 main 函数中调用 USART1_Init() 进行串口初始化。
-
调用 USART1_SendChar() 或 USART1_SendString() 发送数据。
-
调用 USART1_ReceiveChar() 接收单个字符。
-
在中断处理函数 USART1_IRQHandler() 中处理接收到的数据。
注意事项:
-
需要先配置对应的 GPIO 引脚为复用推挽输出模式,才能使用 USART 功能。
-
在发送数据时,需要等待 USART_SR_TXE 标志位置位,表示数据寄存器为空,才能继续发送。
-
在接收数据时,需要等待 USART_SR_RXNE 标志位置位,表示数据寄存器非空,才能继续接收。
原文地址: https://www.cveoy.top/t/topic/rtx 著作权归作者所有。请勿转载和采集!