简述
如前几篇所说, 使用BearPi Std板进行学习测试, 本例
开发板 : Bearpi Std(小熊派标准板)
主芯片: STM32L431RCT6
LED : PC13 \ 推挽输出即可 \ 高电平点亮
串口: Usart1
步骤
- 打开 STM32CubeMX
- 如 BearPi Std 板从入门到放弃 - 引气入体篇(1)(由零创建工程到点亮LED) 先创建项目
- 串口配置
如图所示, 将串口配置为 异步模式
启用串口中断
- 生成代码
- 先编译
- 加入用户代码
int main(void)
{
/* USER CODE BEGIN 1 */
uint32_t count = 0;
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
HAL_UART_Receive_IT(&huart1, &recvData, 1);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_Delay(1000);
HAL_GPIO_TogglePin(USER_LED_GPIO_Port, USER_LED_Pin);
++count;
printf("time %d \r\n", count);
if (10000 == count)
{
count = 0;
}
}
/* USER CODE END 3 */
}
/* USER CODE BEGIN 4 */
/* 实现中断接收回调处理 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
HAL_UART_Transmit(&huart1, &recvData, 1, 0xff);
HAL_UART_Receive_IT(&huart1, &recvData, 1);
}
/* USER CODE END 4 */
前言后说
有兴趣看下 usart.h 的函数, 涉及到的函数如下
HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout); // 常规发送
HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); // 常规接收
HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size);// 中断发送
HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); // 中断接收
HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size);// DMA发送
HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); // DMA接收
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); // 中断回调,在回调中接收数据
HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); // 中断接收数据, 调用之后当有数据时触发中断回调函数