两个stm32之间串口通信代码怎么写
时间: 2024-12-17 16:55:19 浏览: 12
在STM32之间通过串口通信,通常会使用HAL库提供的功能。这里是一个基本的例子,展示如何在两个STM32设备上设置USART通信:
```c
#include "stm32f1xx_hal.h"
// 设定发送端和接收端的USART句柄
USART_HandleTypeDef UsartSend;
USART_HandleTypeDef UsartRecv;
void USART_Init(USART_HandleTypeDef* USARTx, uint32_t BaudRate)
{
// 初始化发送端
USART_InitStruct.BaudRate = BaudRate;
USART_InitStruct.WordLength = UART_WordLength_8b;
USART_InitStruct.StopBits = UART_StopBits_1;
USART_InitStruct.Parity = UART_Parity_No;
USART_InitStruct.Mode = UART_Mode_Tx | UART_Mode_Rx;
USART_InitStruct.HwFlowControl = UART_HardwareFlowControl_None;
USART_InitStruct.RxBufferSize = 1;
USART_InitStruct.TxBufferSize = 1;
HAL_UART_Init(USARTx);
// 初始化接收端
USART_InitStruct.BaudRate = BaudRate; // 如果需要双向通信,双方都设置相同的波特率
// 其他配置保持一致
HAL_UART_Init(&UsartRecv);
}
void USART_Transmit(uint8_t *txData, uint16_t length, USART_HandleTypeDef* USARTx)
{
while (length > 0)
{
HAL_UART_Transmit(USARTx, txData++, 1, HAL_MAX_DELAY);
length--;
}
}
uint8_t USART_Receive(uint8_t *rxBuffer, uint16_t size, USART_HandleTypeDef* USARTx)
{
uint16_t receivedSize = 0;
if (HAL_UART_ReceiveNonBlocking(USARTx, rxBuffer, size, &receivedSize) != HAL_OK)
{
return 0; // 没有数据可用
}
return receivedSize;
}
int main(void)
{
USART_Init(&UsartSend, 9600); // 设置发送端和接收端的波特率为9600
USART_Init(&UsartRecv, 9600);
uint8_t txData[] = { 'H', 'e', 'l', 'l', 'o', '\r', '\n' };
uint8_t rxBuffer[10];
// 发送数据
USART_Transmit(txData, sizeof(txData), &UsartSend);
// 接收数据并打印
while (USART_Receive(rxBuffer, sizeof(rxBuffer), &UsartRecv))
{
for (int i = 0; i < rxBuffer[receivedSize]; i++)
printf("%c", rxBuffer[i]);
}
// 等待接收方完成处理
HAL_Delay(1000);
return 0;
}
```
阅读全文