其他分享
首页 > 其他分享> > stm32 USART

stm32 USART

作者:互联网

stm32 USART

1 USART基础知识

三种模式:轮询模式、中断模式、DMA模式

轮询模式属于阻塞模式

中断模式和DMA模式属于非阻塞模式

发送数据

接收数据

1.1 Polling mode IO operation

1.2 Interrupt mode IO operation

1.3 DMA mode IO operation

2 重定向USART的输入与输出


//!配置好printf重定向的源文件。(有一处需要结合实际替换)
//!开启usart中断时:需要在主循环之前手动开启接收中断:HAL_UART_Receive_IT(&huart1, (uint8_t *)aRxBuffer, 1);
// 调用scanf在串口助手中输入数据时,必须以空格结束(或者回车与换行),然后点击发送,否则无法完成发送。
#include "stdio.h"

//!retarget printf()(fputc() series)
//!huart1 may need to be changed
int fputc(int ch, FILE * f)
{
	HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
	return ch;
}

//!retarget scanf()(fgetc() series)
//!huart1 may need to be changed
int fgetc(FILE *f)
{
	uint8_t ch=0;
	HAL_UART_Receive(&huart1,&ch, 1, 0xffff);
	return ch;
}


//* printf重定向
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
//! 直接printf("HelloWorld");会导致打印不出来,自觉加/r/n
PUTCHAR_PROTOTYPE
{
    //具体哪个串口可以更改huart1为其它串口
    HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1 , 0xffff);
    return ch;
}

3 USART中断

//The specific UART interrupts (Transmission complete interrupt, RXNE interrupt
//and Error Interrupts) will be managed using the macros
//__HAL_UART_ENABLE_IT() and __HAL_UART_DISABLE_IT() inside the
//transmit and receive process.

//【注】:实际上使能中断的(宏)函数是__HAL_UART_ENABLE_IT只不过该函数在HAL_UART_Receive_IT和HAL_UART_Transmit_IT中被调用了。

#define buffsize 5 
uint8_t buff[10];

HAL_UART_Receive_IT(&huart1,buff,buffsize);//可以接收指定长度的字符。任意长度需要使用DMA

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
    if(huart->Instance==USART1){
    	
    }
    HAL_UART_Receive_IT(&huart1,buff,buffsize);
}
if(huart->Instance==USART1){

}

4 其他

标签:DMA,HAL,USART,UART,huart1,stm32,Receive,using
来源: https://www.cnblogs.com/yann-qu/p/15675355.html