本帖最后由 南来之风 于 2024-9-7 13:16 编辑
板载的STlink有虚拟串口通信的功能,连接到H7芯片的PD0与PD1引脚。
在上一次项目的基础上,打开图形化配置界面,配置UART功能。
在Connectivity一栏,找到UART4,然后在右侧配置参数。
默认的引脚不是PD0与PD1,手动更改一下即可。
点击保存,自动生成代码。
static void MX_UART4_Init(void)
{
/* USER CODE BEGIN UART4_Init 0 */
/* USER CODE END UART4_Init 0 */
/* USER CODE BEGIN UART4_Init 1 */
/* USER CODE END UART4_Init 1 */
huart4.Instance = UART4;
huart4.Init.BaudRate = 115200;
huart4.Init.WordLength = UART_WORDLENGTH_8B;
huart4.Init.StopBits = UART_STOPBITS_1;
huart4.Init.Parity = UART_PARITY_NONE;
huart4.Init.Mode = UART_MODE_TX_RX;
huart4.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart4.Init.OverSampling = UART_OVERSAMPLING_16;
huart4.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart4.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart4.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart4) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart4, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart4, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart4) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN UART4_Init 2 */
/* USER CODE END UART4_Init 2 */
}
接下来编写应用程序代码。首先定义好要输出的字符串:/* USER CODE BEGIN 0 */
uint8_t UartTestStr[] = "Hello 21ic, Hello STM32H7S78-DK!";
/* USER CODE END 0 */
主程序中直接调用HAL库的发送API接口:
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MPU Configuration--------------------------------------------------------*/
MPU_Config();
/* MCU Configuration--------------------------------------------------------*/
/* Update SystemCoreClock variable according to RCC registers values. */
SystemCoreClockUpdate();
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_UART4_Init();
/* USER CODE BEGIN 2 */
HAL_UART_Transmit(&huart4, "\r\nUART4 Init Done", sizeof("\r\nUART4 Init Done"), 0xffffffff);
HAL_UART_Transmit(&huart4, UartTestStr, sizeof(UartTestStr), 0xffffffff);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_UART_Transmit(&huart4, "\r\nLD1 GREEN TOGGLE", sizeof("\r\nLD1 GREEN TOGGLE"), 0xffffffff);
HAL_GPIO_TogglePin(LD1_GPIO_PORT, LD1_PIN);
/* Insert delay 100 ms */
HAL_UART_Transmit(&huart4, "\r\nLD2 ORANGE TOGGLE", sizeof("\r\nLD2 ORANGE TOGGLE"), 0xffffffff);
HAL_Delay(1000);
HAL_GPIO_TogglePin(LD2_GPIO_PORT, LD2_PIN);
/* Insert delay 100 ms */
HAL_Delay(1000);
}
/* USER CODE END 3 */
}
打开串口工具TeraTerm,配置串口参数:
实物效果:
|