/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>© Copyright (c) 2025 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "adc.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "string.h" #include "lcd.h" #include <stdio.h> #include "led1.h" #include "uart.h" #include "key.h" #include "flash.h" float distance = 0; char buf[32]; /* 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 key_rval; char lcd_buf[32] = {0}; double volt_R37; double volt_R38; extern uint8_t l2450_rx_data; extern char l2450_rx_buffer[50]; extern uint8_t l2450_rx_index; volatile int16_t x_distance = 0; // ??????? volatile int16_t y_distance = 0; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* 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(); MX_ADC1_Init(); MX_ADC2_Init(); MX_USART2_UART_Init(); /* USER CODE BEGIN 2 */ distance = Flash_LoadDistance(); LCD_Init(); LCD_Clear(White); LCD_SetBackColor(White); LCD_SetTextColor(Black); LCD_DisplayStringLine(Line4, (uint8_t *)"x:---- y:----"); char lcd_buf[32]; sprintf(lcd_buf, "distance:%.1f m", distance); LCD_DisplayStringLine(Line9, (uint8_t*)lcd_buf); UART_StartReceive_IT(); HAL_UART_Receive_IT(&huart2, &l2450_rx_data, 1); HAL_ADCEx_Calibration_Start(&hadc1,ADC_SINGLE_ENDED); HAL_ADCEx_Calibration_Start(&hadc2,ADC_SINGLE_ENDED); volt_R37=getADC2()*3.2/4096; volt_R38=getADC1()*3.2/4096; /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ Key_Proc(); // ???????? static int16_t last_x = 0, last_y = 0; if (x_distance != last_x || y_distance != last_y) { char lcd_buf[32]; float x_m = x_distance / 1000.0f; float y_m = y_distance / 1000.0f; sprintf(lcd_buf, "x:%1.2fm y:%1.2fm", x_m, y_m); LCD_DisplayStringLine(Line4, (uint8_t *)lcd_buf); last_x = x_distance; last_y = y_distance; } HAL_Delay(10); // ????,??LCD???? } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; /** Configure the main internal regulator output voltage */ HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1); /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV3; RCC_OscInitStruct.PLL.PLLN = 20; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } /** Initializes the peripherals clocks */ PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_USART2 |RCC_PERIPHCLK_ADC12; PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2; PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_PCLK1; PeriphClkInit.Adc12ClockSelection = RCC_ADC12CLKSOURCE_SYSCLK; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32g4xx_it.c * @brief Interrupt Service Routines. ****************************************************************************** * @attention * * <h2><center>© Copyright (c) 2025 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32g4xx_it.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include "lcd.h" #include "led1.h" #include "usart.h" #include "uart.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ // ?????? extern UART_HandleTypeDef huart1; extern UART_HandleTypeDef huart2; extern volatile int16_t x_distance; extern volatile int16_t y_distance; extern float distance; // USART2 ?????? extern uint8_t l2450_rx_data; extern char l2450_rx_buffer[50]; extern uint8_t l2450_rx_index; // USART1 ???????? extern uint8_t rx_data; extern char tx_buf[64]; /* USER CODE END TD */ /* 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 */ static uint8_t rec_buf[50]; // ????? static uint8_t rec_index = 0; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* External variables --------------------------------------------------------*/ extern UART_HandleTypeDef huart1; extern UART_HandleTypeDef huart2; /* USER CODE BEGIN EV */ extern UART_HandleTypeDef huart2; extern uint8_t l2450_rx_data; extern char l2450_rx_buffer[50]; extern uint8_t l2450_rx_index; extern float distance; /* USER CODE END EV */ /******************************************************************************/ /* Cortex-M4 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles Non maskable interrupt. */ void NMI_Handler(void) { /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ /* USER CODE END NonMaskableInt_IRQn 0 */ /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ while (1) { } /* USER CODE END NonMaskableInt_IRQn 1 */ } /** * @brief This function handles Hard fault interrupt. */ void HardFault_Handler(void) { /* USER CODE BEGIN HardFault_IRQn 0 */ /* USER CODE END HardFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_HardFault_IRQn 0 */ /* USER CODE END W1_HardFault_IRQn 0 */ } } /** * @brief This function handles Memory management fault. */ void MemManage_Handler(void) { /* USER CODE BEGIN MemoryManagement_IRQn 0 */ /* USER CODE END MemoryManagement_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ /* USER CODE END W1_MemoryManagement_IRQn 0 */ } } /** * @brief This function handles Prefetch fault, memory access fault. */ void BusFault_Handler(void) { /* USER CODE BEGIN BusFault_IRQn 0 */ /* USER CODE END BusFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_BusFault_IRQn 0 */ /* USER CODE END W1_BusFault_IRQn 0 */ } } /** * @brief This function handles Undefined instruction or illegal state. */ void UsageFault_Handler(void) { /* USER CODE BEGIN UsageFault_IRQn 0 */ /* USER CODE END UsageFault_IRQn 0 */ while (1) { /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ /* USER CODE END W1_UsageFault_IRQn 0 */ } } /** * @brief This function handles System service call via SWI instruction. */ void SVC_Handler(void) { /* USER CODE BEGIN SVCall_IRQn 0 */ /* USER CODE END SVCall_IRQn 0 */ /* USER CODE BEGIN SVCall_IRQn 1 */ /* USER CODE END SVCall_IRQn 1 */ } /** * @brief This function handles Debug monitor. */ void DebugMon_Handler(void) { /* USER CODE BEGIN DebugMonitor_IRQn 0 */ /* USER CODE END DebugMonitor_IRQn 0 */ /* USER CODE BEGIN DebugMonitor_IRQn 1 */ /* USER CODE END DebugMonitor_IRQn 1 */ } /** * @brief This function handles Pendable request for system service. */ void PendSV_Handler(void) { /* USER CODE BEGIN PendSV_IRQn 0 */ /* USER CODE END PendSV_IRQn 0 */ /* USER CODE BEGIN PendSV_IRQn 1 */ /* USER CODE END PendSV_IRQn 1 */ } /** * @brief This function handles System tick timer. */ void SysTick_Handler(void) { /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } /******************************************************************************/ /* STM32G4xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32g4xx.s). */ /******************************************************************************/ /** * @brief This function handles USART1 global interrupt / USART1 wake-up interrupt through EXTI line 25. */ void USART1_IRQHandler(void) { /* USER CODE BEGIN USART1_IRQn 0 */ /* USER CODE END USART1_IRQn 0 */ HAL_UART_IRQHandler(&huart1); /* USER CODE BEGIN USART1_IRQn 1 */ /* USER CODE END USART1_IRQn 1 */ } /** * @brief This function handles USART2 global interrupt / USART2 wake-up interrupt through EXTI line 26. */ void USART2_IRQHandler(void) { /* USER CODE BEGIN USART2_IRQn 0 */ /* USER CODE END USART2_IRQn 0 */ HAL_UART_IRQHandler(&huart2); /* USER CODE BEGIN USART2_IRQn 1 */ /* USER CODE END USART2_IRQn 1 */ } /* USER CODE BEGIN 1 */ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if (huart->Instance == USART2) // L2450 ?? { if (rec_index < sizeof(rec_buf)) { rec_buf[rec_index++] = l2450_rx_data; } else { rec_index = 0; } if (rec_index >= 30) { if (rec_buf[0] == 0xAA && rec_buf[1] == 0xFF && rec_buf[2] == 0x03 && rec_buf[3] == 0x00 && rec_buf[28] == 0x55 && rec_buf[29] == 0xCC) { // ???????? uint16_t x_raw = rec_buf[4] | (rec_buf[5] << 8); uint16_t y_raw = rec_buf[6] | (rec_buf[7] << 8); int16_t x_mm = -(int16_t)x_raw; int16_t y_mm = (int16_t)(y_raw - 0x8000); int16_t r = (int16_t)sqrtf(x_mm * x_mm + y_mm * y_mm); if (r >= 1000 && r <= 5000) { x_distance = x_mm; y_distance = y_mm; // ???? LCD ?? char lcd_buf[32]; float x_m = x_distance / 1000.0f; float y_m = y_distance / 1000.0f; sprintf(lcd_buf, "x:%1.2fm y:%1.2fm", x_m, y_m); LCD_DisplayStringLine(Line4, (uint8_t *)lcd_buf); } rec_index = 0; } else { // ?????,??1??? memmove(rec_buf, rec_buf + 1, rec_index - 1); rec_index--; } } HAL_UART_Receive_IT(&huart2, &l2450_rx_data, 1); } else if (huart->Instance == USART1) // ??1(???????) { UART_ReceiveCallback(rx_data); HAL_UART_Receive_IT(&huart1, &rx_data, 1); } } /* USER CODE END 1 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ 修改代码,.毫米波模块测量前面1-5m的物体。毫米波模块连接到UART2 ,,检测到的信息实时显示在LCD上
时间: 2025-07-08 07:47:15 浏览: 12
为了实现STM32通过UART2检测1-5米内物体距离并将信息实时显示在LCD上,需要对硬件和软件部分进行配置。以下是一个详细的步骤指南:
### 硬件配置
1. **主控芯片**:使用STM32F103RCT6作为主控芯片。
2. **毫米波雷达模块**:选择支持UART通信的毫米波雷达模块,并将其连接到STM32的UART2接口。
3. **显示屏**:使用1.44寸TFT LCD显示屏来显示检测结果。
### 软件配置
1. **初始化UART2**:配置UART2以接收来自毫米波雷达的数据。
2. **解析数据**:从毫米波雷达接收到的数据中提取物体的距离信息。
3. **更新LCD显示**:将解析得到的距离信息实时显示在TFT LCD上。
### 示例代码
以下是一个简单的示例代码,展示如何通过UART2读取毫米波雷达的数据并将其显示在LCD上:
```c
#include "stm32f10x.h"
#include "lcd.h"
#include "stdio.h"
#define MAX_BUFFER_SIZE 128
uint8_t rx_buffer[MAX_BUFFER_SIZE];
uint8_t data_ready = 0;
uint16_t distance = 0;
void UART2_Init(void) {
// Enable USART2 and GPIOA clock
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// Configure USART2 Tx (PA2) as alternate function push-pull
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// Configure USART2 Rx (PA3) as input floating
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// Configure USART2
USART_InitTypeDef USART_InitStruct;
USART_InitStruct.USART_BaudRate = 9600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStruct);
// Enable USART2
USART_Cmd(USART2, ENABLE);
// Enable USART2 RXNE interrupt
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
// Enable USART2 global interrupt
NVIC_EnableIRQ(USART2_IRQn);
}
void USART2_IRQHandler(void) {
if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) {
static uint8_t index = 0;
uint8_t ch = USART_ReceiveData(USART2);
if (index < MAX_BUFFER_SIZE - 1) {
rx_buffer[index++] = ch;
if (ch == '\n') { // Assuming each data packet ends with newline character
rx_buffer[index] = '\0';
index = 0;
data_ready = 1;
}
} else {
index = 0; // Reset buffer on overflow
}
}
}
void parse_distance(void) {
if (data_ready) {
// Example format: "Distance: 123 cm\n"
char *start = (char *)rx_buffer;
char *end;
distance = (uint16_t)strtol(start + 9, &end, 10); // Adjust parsing based on actual data format
data_ready = 0;
}
}
int main(void) {
// Initialize UART2
UART2_Init();
// Initialize LCD
LCD_Init();
LCD_Clear(WHITE);
while (1) {
parse_distance();
if (distance > 0 && distance <= 500) { // Check if distance is within 1-5 meters (100-500 cm)
char buffer[32];
sprintf(buffer, "Distance: %d cm", distance);
LCD_DisplayStringLine(LCD_LINE_3, (uint8_t *)buffer);
} else {
LCD_DisplayStringLine(LCD_LINE_3, (uint8_t *)"No object detected");
}
}
}
```
### 说明
1. **UART2初始化**:配置UART2以9600波特率工作,并启用中断以便于接收数据。
2. **中断处理**:在`USART2_IRQHandler`函数中接收数据,并存储到缓冲区中,当接收到换行符时标记数据就绪。
3. **解析数据**:在`parse_distance`函数中解析缓冲区中的距离数据。
4. **显示数据**:在主循环中检查是否有新的距离数据,并将其显示在LCD上。
请根据实际使用的毫米波雷达模块的数据格式调整解析逻辑。此外,确保LCD驱动程序已正确实现并可以正常工作。
### 注意事项
- 确保毫米波雷达模块的供电电压与STM32兼容。
- 检查UART通信参数(如波特率)是否与毫米波雷达模块匹配。
- 根据实际需求调整LCD显示内容和位置。
阅读全文
相关推荐














