目录
一、轮询模式
1.1 配置USART2为异步模式
1.2 500ms发送一次消息
1.3 通信结果
1.4 串口控制LED
二、中断收发
2.1 开启中断
2.2 中断发送接收
2.2.1 中断发送只需要调用接口
2.2.2 中断接收
2.3 实验结果
三、DMA模式与收发不定长数据
3.1 DMA通道配置
3.2 DMA发送接收函数
3.3 使用空闲中断接收不定长数据
一、轮询模式
1.1 配置USART2为异步模式
1.2 500ms发送一次消息
1.3 通信结果
1.4 串口控制LED
uint8_t reciveDate[2];
while (1)
{
HAL_UART_Receive(&huart1, reciveDate, 2, HAL_MAX_DELAY);
HAL_UART_Transmit(&huart1, reciveDate, 2, 100);
GPIO_PinState state=GPIO_PIN_SET;
if(reciveDate[1]=='1')
{
state=GPIO_PIN_RESET;
}
if(reciveDate[0]=='R')
{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, state);
}
else if(reciveDate[0]=='G')
{
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, state);
}
}
}
二、中断收发
2.1 开启中断
2.2 中断发送接收
2.2.1 中断发送只需要调用接口
HAL_UART_Transmit_IT(&huart1, reciveDate, 2);
2.2.2 中断接收
①在程序起始开启中断
②重新定义stm32f1xx_hal_uart.c中的函数
__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(huart);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_UART_RxCpltCallback could be implemented in the user file
*/
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
HAL_UART_Transmit_IT(&huart1, reciveDate, 2);
GPIO_PinState state = GPIO_PIN_SET;
if (reciveDate[1] == '1')
{
state = GPIO_PIN_RESET;
}
if (reciveDate[0] == 'G')
{
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, state);
}
HAL_UART_Receive_IT(&huart1, reciveDate, 2);//再次启动中断接收
}
2.3 实验结果
三、DMA模式与收发不定长数据
3.1 DMA通道配置
3.2 DMA发送接收函数
只需要将_IT修改为_DMA即可,DMA模式还是有中断参与其中
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
HAL_UART_Transmit_DMA(&huart1, reciveDate, 2);//dma发送
GPIO_PinState state = GPIO_PIN_SET;
if (reciveDate[1] == '1')
{
state = GPIO_PIN_RESET;
}
if (reciveDate[0] == 'G')
{
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, state);
}
HAL_UART_Receive_DMA(&huart1, reciveDate, 2);//DMA接收
}
3.3 使用空闲中断接收不定长数据
只有当接收端不再有数据输入时才会触发空闲中断,重新定义
__weak void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(huart);
UNUSED(Size);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_UARTEx_RxEventCallback can be implemented in the user file.
*/
}
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
if(huart==&huart1)
{
HAL_UART_Transmit_DMA(&huart1, reciveDate, Size);//发�?�与接收相同的Size长度的字节数
HAL_UARTEx_ReceiveToIdle_DMA(&huart1, reciveDate, sizeof(reciveDate));//接收不定长数�?
}
}