1、任务描述
使用freertos系统实现电脑调试助手和正点原子开发板STM32F103ZET6的串口通信。
2、cubemx设置
3、程序代码
(1)添加usart1.c
#include "usart1.h"#include "usart.h"/**********重定义函数**********/struct __FILE
{int handle;};FILE __stdout;
//定义_sys_exit()以避免使用半主机模式
void _sys_exit(int x)
{x = x;
}
//重定义fputc函数
int fputc(int ch, FILE *f)
{while((USART1->SR&0X40)==0);//循环发送,直到发送完毕USART1->DR = (uint8_t) ch;return ch;
}//串口1发送串口屏数据send_data
void UserUart1Send(uint8_t *send_data,uint8_t send_len)
{while(send_len--){HAL_UART_Transmit(&huart1,send_data++,1,20);}
}
(2)main.c中
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */#include "usart1.h"/* USER CODE END Includes *//* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD *//* USER CODE END PTD *//* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD *//* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM *//* USER CODE END PM *//* Private variables ---------------------------------------------------------*//* USER CODE BEGIN PV */uint8_t Buffer[13]="hello world\r\n";uint8_t pre_rec_buf[10];uint8_t flag=0;/* USER CODE END PV *//* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP *//* USER CODE END PFP *//* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 *///接收回调函数---接收气压数值字符
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){if(huart==&huart1){// HAL_UART_Receive_IT(&huart1,(uint8_t*)pre_rec_buf,20);flag=1;
// HAL_UART_Transmit_IT(&huart1,Buffer,sizeof(Buffer),11);
// UserUart1Send(Buffer,sizeof(Buffer));
// memset(pre_rec_buf,0,22);// count=0;}HAL_UART_Receive_IT(&huart1,(uint8_t*)pre_rec_buf,10);}/* USER CODE END 0 *//*** @brief The application entry point.* @retval int*/
int main(void)
{/* USER CODE BEGIN 1 *//* USER CODE END 1 *//* MCU Configuration--------------------------------------------------------*//* Reset of all peripherals, Initializes the Flash interface and the Systick. */HAL_Init();/* USER CODE BEGIN Init *//* USER CODE END Init *//* Configure the system clock */SystemClock_Config();/* USER CODE BEGIN SysInit *//* USER CODE END SysInit *//* Initialize all configured peripherals */MX_GPIO_Init();MX_USART1_UART_Init();/* USER CODE BEGIN 2 */HAL_UART_Receive_IT(&huart1,(uint8_t*)pre_rec_buf,10);/* USER CODE END 2 */
(3)freertos.c中
/* USER CODE END Header_usart_Task02 */
void usart_Task02(void *argument)
{/* USER CODE BEGIN usart_Task02 *//* Infinite loop */for(;;){if(flag==1){UserUart1Send(Buffer,sizeof(Buffer));flag=0;}// osDelay(1);}/* USER CODE END usart_Task02 */
}
4、调试结果