最近学到了串口收发,简单记录一下注意事项。
以使用USART1为例。
USART1需配置成异步工作模式Asynchronous。
并且需要使能NVIC。
我偏向于在stm32f1xx_it.c文件中对printf进行重定向,重定向函数如下。
int fputc(int ch,FILE * fp)
{
HAL_UART_Transmit(&huart1,(uint8_t * )&ch,1,0xffff);
return ch;
}
同时需包含头文件路径#include “stdio.h”
在工程属性Target下,勾选Use MicroLIB。
至此,可以由printf语句经USART1发送数据了。
/* USER CODE BEGIN Private defines */
#define USART_REC_LEN 200
#define RXBUFFERSIZE 1
extern uint16_t USART_RX_STA;
extern uint8_t USART_RX_BUF[USART_REC_LEN];
extern uint8_t aRxBuffer[RXBUFFERSIZE];
/* USER CODE END Private defines */
HAL_UART_Receive_IT(&huart1, (uint8_t *)aRxBuffer, RXBUFFERSIZE);
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance==USART1)//
{
if((USART_RX_STA&0x8000)==0)//
{
if(USART_RX_STA&0x4000)//
{
if(aRxBuffer[0]!=0x0a)USART_RX_STA=0;//
else USART_RX_STA|=0x8000; //
}
else //
{
if(aRxBuffer[0]==0x0d)USART_RX_STA|=0x4000;
else
{
USART_RX_BUF[USART_RX_STA&0X3FFF]=aRxBuffer[0] ;
USART_RX_STA++;
if(USART_RX_STA>(USART_REC_LEN-1))USART_RX_STA=0;//
}
}
}
}
}
void USART1_IRQHandler(void)
{
uint32_t timeout=0;
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
timeout=0;
while (HAL_UART_GetState(&huart1) != HAL_UART_STATE_READY)//
{
timeout++;//
if(timeout>HAL_MAX_DELAY) break;
}
timeout=0;
while(HAL_UART_Receive_IT(&huart1, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)//Ò»´Î´¦ÀíÍê³ÉÖ®ºó£¬ÖØпªÆôÖжϲ¢ÉèÖÃRxXferCountΪ1
{
timeout++; //³¬Ê±´¦Àí
if(timeout>HAL_MAX_DELAY) break;
}
/* USER CODE END USART1_IRQn 1 */
}
while (1)
{
uint8_t len=0;
static uint16_t times = 0;
printf("%d\r\n",times++);
HAL_Delay(500);
HAL_GPIO_TogglePin(GPIOB,GPIO_PIN_5);
HAL_GPIO_TogglePin(GPIOE,GPIO_PIN_5);
if(USART_RX_STA&0x8000)
{
len=USART_RX_STA&0x3fff;//µÃµ½´Ë´Î½ÓÊÕµ½µÄÊý¾Ý³¤¶È
printf("\r\nÄú·¢Ë͵ÄÏûϢΪ:\r\n");
HAL_UART_Transmit(&huart1,(uint8_t*)USART_RX_BUF,len,1000); //·¢ËͽÓÊÕµ½µÄÊý¾Ý
while(__HAL_UART_GET_FLAG(&huart1,UART_FLAG_TC)!=SET); //µÈ´ý·¢ËͽáÊø
printf("\r\n\r\n");//²åÈë»»ÐÐ
USART_RX_STA=0;
}
else
{
if(times%20==0)printf("ÇëÊäÈëÊý¾Ý,ÒԻسµ¼ü½áÊø\r\n");
if(times%2==0);//LED0=!LED0;//ÉÁ˸LED,ÌáʾϵͳÕýÔÚÔËÐÐ.
}
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}