写·一个stm32f103hal库串口接收数据的代码源码
时间: 2024-12-15 20:16:43 浏览: 30
正点原子stm32f103 HAL库版本示例程序
在STM32F103 HAL库中,通过HAL库提供的功能来管理串口通信通常涉及以下几个步骤。以下是一个简化的示例,展示了如何初始化并接收数据:
```c
#include "stm32f1xx_hal.h"
#include "stdio.h"
// 初始化串口句柄
void MX_USART1_UART_Init(void)
{
USART_HandleTypeDef huart1;
// 配置串口
huart1.Instance = USART1;
huart1.Init.BaudRate = 9600; // 设置波特率
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowControl = UART_HWCONTROL_NONE;
huart1.Init.RxRingBufferLength = UART_RECEIVE_LENGTH_16B;
// 初始化并开启串口
if (HAL_UART_Init(&huart1) != HAL_OK)
{
while(1); // 程序终止,因为初始化失败
}
}
// 主循环中的串口接收函数
uint8_t ReceiveData()
{
uint8_t data = 0;
HAL_StatusTypeDef status = HAL_UART_Receive(&huart1, &data, 1, 1000); // 接收1字节数据
if(status == HAL_OK)
{
return data; // 返回接收到的数据
}
else if(status == HAL_TIMEOUT)
{
printf("Timeout!\n");
return 0; // 数据未接收成功,返回0
}
else
{
printf("Error receiving data: %d\n", status);
return 0; // 发生错误,返回0
}
}
int main(void)
{
// 先初始化硬件资源
MX_USART1_UART_Init();
while (1)
{
uint8_t received_char = ReceiveData();
if(received_char != 0)
{
printf("Received character: %u\n", received_char);
}
}
return 0;
}
```
阅读全文