STM32之旅4——USART

STM32之旅4——USART

串口也是用的比较多的,在STM32CubeMX中生成代码后,需要添加一些代码才可以用。

drv_usart.h:

#ifndef __DRV_USART_H
#define __DRV_USART_H

#define USART1_MAX_LEN 64						//接收区长度
#define USART1_BUFF_CACHE_LEN 1					//接收缓冲区长度

extern uint16_t g_usart1_sta;					//接收状态[1:15],最高位为接收完成标志
extern uint8_t g_usart1_buff[USART1_MAX_LEN];						//接收buff
extern uint8_t g_usart1_buff_cache[USART1_BUFF_CACHE_LEN];			//接收缓存

#endif

使用printf()发送的时候需要重定向,没有fputc()是不行的;使用中断接收的时候,并不是在USART1_IRQHandler()里面添加代码,而是在回调函数HAL_UART_RxCpltCallback()中写,接收完成时要在后面加上HAL_UART_Receive_IT(),串口初始化时也要加上HAL_UART_Receive_IT(),否则不能进中断。

drv_usart.c:

#include "stm32f1xx.h"
#include "drv_usart.h"
#include "stdio.h"
#include "usart.h"

uint16_t g_usart1_sta;//接收状态[1:15],最高位为接收完成标志
uint8_t g_usart1_buff[USART1_MAX_LEN];
uint8_t g_usart1_buff_cache[USART1_BUFF_CACHE_LEN];

/***********printf函数重写,有了这个函数就可以使用printf()发送串口数据了**********/
int fputc(int ch,FILE *f)
{
    uint8_t temp[1]={ch};
    HAL_UART_Transmit(&huart1,temp,1,2);

    return 0;
}
/****************************串口中断回调函数*************************************/
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(USART1 == huart->Instance)
    {
          if(0 == (g_usart1_sta & 0x8000))//接收未完成
          {
                g_usart1_buff[g_usart1_sta++] = g_usart1_buff_cache[0];

                if(0x0A == g_usart1_buff_cache[0])//如果接收到回车,就接收完成
                {
		    g_usart1_sta |= 0x8000;
                }
          }
          HAL_UART_Receive_IT(&huart1,(uint8_t *)g_usart1_buff_cache,USART1_BUFF_CACHE_LEN);
    }
}

这里没加HAL_UART_Receive_IT()是不会进进中断的。

usart.c:

void MX_USART1_UART_Init(void)
{
    huart1.Instance = USART1;
    huart1.Init.BaudRate = 115200;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    if (HAL_UART_Init(&huart1) != HAL_OK)
    {
          Error_Handler();
    }
    HAL_UART_Receive_IT(&huart1,g_usart1_buff_cache,USART1_BUFF_CACHE_LEN);
}
posted @ 2020-08-08 14:44  曾经梦想少年  阅读(239)  评论(0编辑  收藏  举报