STM32串口配置库函数
时间: 2023-07-20 17:28:49 浏览: 89
在STM32 MCU中,串口是非常重要的通信接口。为了方便使用,ST官方提供了一套串口配置库函数,可以帮助开发者轻松配置串口参数和进行数据传输。下面是一个简单的使用STM32串口配置库函数的示例代码:
```
#include "stm32f4xx_hal.h"
UART_HandleTypeDef huart2;
void SystemClock_Config(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
__HAL_RCC_USART2_CLK_ENABLE();
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
HAL_UART_Init(&huart2);
while (1)
{
char tx_data[] = "Hello, world!\n";
HAL_UART_Transmit(&huart2, (uint8_t*)tx_data, sizeof(tx_data), 1000);
char rx_data[16];
HAL_UART_Receive(&huart2, (uint8_t*)rx_data, sizeof(rx_data), 1000);
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1
|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
}
```
这段代码使用了HAL库函数来配置串口参数和进行数据传输。具体来说,它使用了USART2接口,设置了波特率为115200,数据位为8位,停止位为1位,无奇偶校验,发送和接收模式均开启。然后在while循环中,通过`HAL_UART_Transmit`函数发送一段字符串,然后通过`HAL_UART_Receive`函数接收一段字符串并存储到缓冲区中。开发者可以根据实际需要进行修改和扩展。
阅读全文