stm32G431 串口通信例程hal库
时间: 2023-08-18 09:06:50 浏览: 149
stm32与中显串口屏通信1:hal库点灯
5星 · 资源好评率100%
请将以下代码复制到main.c的/* USER CODE BEGIN 0 */和/* USER CODE END 0 */之间。
```c
uint8_t uart_rx_buf == 'a') { // 接收到数据'a',回应"Hello"
printf("Hello\r\n");
}
HAL_UART_Receive_IT(&huart1, uart_rx_buf, 1); // 设置串口中断缓冲区及中断阈值(当前为1)
}
// 重定向printf函数为串口输出
int fputc(int ch, FILE *p) {
char c = ch;
HAL_UART_Transmit(&huart1, (unsigned char *)&c, 1, 50);
return ch;
}
// 发送单个数据
void UART1_SendByte(char c) {
HAL_UART_Transmit(&huart1, (unsigned char *)&c, 1, 50);
}
// 发送整个数组
void UART1_SendData(char *p, int len) {
HAL_UART_Transmit(&huart1, (unsigned char *)p, len, 50);
}
```
这段代码实现了在STM32G431上使用HAL库进行串口通信的例程。其中,通过`HAL_UART_RxCpltCallback`函数实现了串口接收数据的中断,当接收到数据为'a'时,回应"Hello"。通过重定向`fputc`函数,将`printf`函数的输出重定向到串口。`UART1_SendByte`函数用于发送单个数据,`UART1_SendData`函数用于发送整个数组。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [【国信长天蓝桥杯】⑤ STM32G431 UART串口收发数据,串口通信示例代码,串口使用步骤,printf重定向](https://blog.csdn.net/weixin_48033504/article/details/115551975)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [STM32G431——串口通信](https://blog.csdn.net/m0_65088451/article/details/128811627)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [STM32G431RB--基于HAL库(蓝桥杯嵌入式赛前梳理)](https://blog.csdn.net/Octopus1633/article/details/124041090)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文