串口通信,算是比较基本的通信方式了,也是比较常用的观察数据的方式。在测试USART和LPUART时,同一时钟,波特率9600时,USART能用,LPUART不能通信,115200时可以,后来翻看参考手册时发现,如图1所示:
连接图如图2所示:
所以这是实践中要注意的。还是老习惯,先初始化引脚: - GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
- GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
- GPIO_InitStruct.Pull = GPIO_PULLUP;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
- GPIO_InitStruct.Alternate = GPIO_AF7_USART2;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
复制代码
初始化UART: - huart2.Instance = USART2;
- huart2.Init.BaudRate = 9600;
- huart2.Init.WordLength = UART_WORDLENGTH_8B;
- huart2.Init.StopBits = UART_STOPBITS_1;
- huart2.Init.Parity = UART_PARITY_NONE;
- huart2.Init.Mode = UART_MODE_TX_RX;
- huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
- huart2.Init.OverSampling = UART_OVERSAMPLING_16;
- huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
- huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
- if (HAL_UART_Init(&huart2) != HAL_OK)
- {
- Error_Handler();
- }
- if(HAL_UART_Receive_IT(&huart2, (uint8_t *)Rxbuf, 2) != HAL_OK)
- {
- Error_Handler();
- }
复制代码
使能接收中断: - /* Peripheral interrupt init */
- HAL_NVIC_SetPriority(USART2_IRQn, 0, 0);
- HAL_NVIC_EnableIRQ(USART2_IRQn);
复制代码
发送部分: HAL_UART_Transmit(&huart2,Txbuf,2,10);
HAL_Delay(2000);
使用串口猎人,来观察发的数据和接收的数据,如图3所示:
|