Control-StraightLine Code

博客介绍了让代码依赖关系更明显的方法,包括组织代码、命名例程、使用例程参数、用注释记录不明确依赖、用断言或错误处理代码检查依赖等,还提及了顺序无关紧要的事项,如让代码从上到下阅读、分组相关语句。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Statement that must be in a specific order
1. Organize code so that dependencies are obvious.
2. Name routines so that dependencies are obvious.
3. Use routine parameters to make dependencies obvious.
4. Document unclear dependencies with comments.
5. Check for dependencies with assertions or error-handling code.

Statments whose order doesn't matter.
1. Making code read from top to bottom.
2. Grouping related statments.

main.c /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2025 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "i2c.h" #include "tim.h" #include "usart.h" #include "gpio.h" #include "jy61p.h" #include "pid.h" #include "kalman_filter.h" #include "motor.h" #include "encoder.h" #include "ultrasonic.h" #include "motion.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "stdio.h" #include "string.h" // Ô²ÖùÐÅÏ¢½á¹¹Ìå #define MAX_CYLINDERS 10 typedef struct { int x, y, r; char color; } Cylinder; Cylinder cylinders[MAX_CYLINDERS]; int cylinder_count = 0; uint8_t rx_byte; char openmv_buffer[128]; uint8_t openmv_index = 0; uint32_t start_time = 0; uint32_t timeout = 10000; // 10s /* 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 */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ void SetTargetYaw(float angle); void AddCylinder(int x, int y, int r, char color); void Path_AroundCylinder(char color); void BuildPath(void); void StartMission(void); uint8_t IsMissionTimeout(void); int CheckColumnSwap(void); void HandleColumnSwap(void); /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ // Ä£¿éÊý¾Ý½á¹¹Ìå JY61P_Data imu_data; PID_Controller speed_pid, angle_pid; KalmanFilter kf; // ¿ØÖƲÎÊý float target_speed = 100; float base_pwm = 70; float dt = 0.01; // ¿ØÖÆÖÜÆÚ/Ãë void Control_Straight(void); void Move_Forward(float cm); void Turn_Left(float angle); void Turn_Right(float angle); // PID ¿ØÖÆÖ±ÐÐ void Control_Straight(void) { float left_speed = Get_Left_Encoder(); float right_speed = Get_Right_Encoder(); float error = left_speed - right_speed; float correction = PID_Update(&angle_pid, error, dt); float left_pwm = base_pwm + correction; float right_pwm = base_pwm - correction; Motor_SetSpeed(left_pwm, right_pwm); } // PID ¿ØÖÆ×ªÏòº¯Êý void SetTargetYaw(float angle) { printf("Turning %.1f degrees\n", angle); HAL_Delay(500); } // Ìí¼ÓÔ²Öùµ½µØÍ¼ void AddCylinder(int x, int y, int r, char color) { if (cylinder_count < MAX_CYLINDERS) { cylinders[cylinder_count].x = x; cylinders[cylinder_count].y = y; cylinders[cylinder_count].r = r; cylinders[cylinder_count].color = color; cylinder_count++; } } // ÈÆÏß·¾¶ void Path_AroundCylinder(char color) { if (color == 'W') { SetTargetYaw(-180.0f); // °××ó } else if (color == 'B') { SetTargetYaw(180.0f); // ºÚÓÒ } } // ¹¹½¨Â·¾¶ void BuildPath() { for (int i = 0; i < cylinder_count; i++) { Path_AroundCylinder(cylinders[i].color); } } //¿ªÊ¼¼ÆÊ± void StartMission() { start_time = HAL_GetTick(); } // ÊÇ·ñ³¬Ê± uint8_t IsMissionTimeout() { return (HAL_GetTick() - start_time) > timeout; } // ¼ì²âÔ²ÖùÊÇ·ñ»¥»» int CheckColumnSwap() { for (int i = 0; i < cylinder_count; i++) { if (cylinders[i].x == 3 && cylinders[i].color == 'B') { return 1; } } return 0; } //´¦ÀíÖù×Ó»¥»» void HandleColumnSwap() { if (CheckColumnSwap()) { printf("Öù×ÓλÖñ仯£¬ÖØÐ¹滮·Ïß...\n"); BuildPath(); // ÖØÐÂÈÆÖù } } //´®¿Ú½ÓÊջص÷ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if (huart == &huart1) { if (rx_byte == '\n') { openmv_buffer[openmv_index] = '\0'; openmv_index = 0; if (strncmp(openmv_buffer, "C ", 2) == 0) { int x, y, r; char color; sscanf(openmv_buffer, "C %d %d %d %c", &x, &y, &r, &color); AddCylinder(x, y, r, color); Path_AroundCylinder(color); } } else { openmv_buffer[openmv_index++] = rx_byte; } HAL_UART_Receive_IT(&huart1, &rx_byte, 1); } } /* 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_I2C1_Init(); MX_TIM2_Init(); MX_TIM3_Init(); MX_TIM4_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ HAL_UART_Receive_IT(&huart1, &rx_byte, 1); StartMission(); //Æô¶¯±àÂëÆ÷¼ÆÊý HAL_TIM_Encoder_Start(&htim3, TIM_CHANNEL_ALL); HAL_TIM_Encoder_Start(&htim4, TIM_CHANNEL_ALL); // ³õʼ»¯ IMU JY61P_Init(&hi2c1); // ³õʼ»¯ PID PID_Init(&speed_pid, 1.0f, 0.1f, 0.05f); PID_Init(&angle_pid, 2.0f, 0.0f, 0.1f); // ³õʼ»¯ ¿¨¶ûÂüÂ˲¨ KalmanFilter_Init(&kf, 0.001f, 0.003f, 0.03f); // Æô¶¯ PWM Êä³ö HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ while (1) { float left = Get_Left_Distance(); float right = Get_Right_Distance(); if (left > 10.0f && right > 10.0f) { Control_Straight(); // Ö±ÐпØÖÆ } else { Motor_Stop(); // Í£Ö¹ if (left > right) Turn_Left(90); // ×óת else Turn_Right(90); // ÓÒת Move_Forward(20); // ǰ½ø20cm Turn_Right(90); // »ØÕý Move_Forward(20); // ¼ÌÐøÇ°½ø } Send_Debug_Info(); // ´®¿ÚÊä³öµ÷ÊÔÐÅÏ¢ HAL_Delay(10); // 10ms ÑÓʱ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** 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.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != 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 */ encoder.c #include "encoder.h" #include "main.h" #include "tim.h" int16_t Get_Left_Encoder(void) { return (int16_t)__HAL_TIM_GET_COUNTER(&htim3); } int16_t Get_Right_Encoder(void) { return (int16_t)__HAL_TIM_GET_COUNTER(&htim4); } jy61p.c#include "jy61p.h" #include <string.h> #define JY61P_ADDRESS 0xA0 void JY61P_Init(I2C_HandleTypeDef *hi2c) {} float JY61P_Read_Float(I2C_HandleTypeDef *hi2c, uint8_t reg) { uint8_t tx_data = reg; uint8_t rx_data[4]; HAL_I2C_Master_Transmit(hi2c, JY61P_ADDRESS, &tx_data, 1, HAL_MAX_DELAY); HAL_I2C_Master_Receive(hi2c, JY61P_ADDRESS, rx_data, 4, HAL_MAX_DELAY); float value; memcpy(&value, rx_data, sizeof(float)); return value; } void JY61P_Read_Data(I2C_HandleTypeDef *hi2c, JY61P_Data *data) { data->yaw = JY61P_Read_Float(hi2c, 0x34); data->pitch = JY61P_Read_Float(hi2c, 0x32); data->roll = JY61P_Read_Float(hi2c, 0x30); } klman_filter.c #include "kalman_filter.h" void KalmanFilter_Init(KalmanFilter *kf, float Q_angle, float Q_gyro, float R_angle) { kf->theta = 0.0f; kf->omega = 0.0f; kf->P[0][0] = 1.0f; kf->P[0][1] = 0.0f; kf->P[1][0] = 0.0f; kf->P[1][1] = 1.0f; kf->Q_angle = Q_angle; kf->Q_gyro = Q_gyro; kf->R_angle = R_angle; } float KalmanFilter_Update(KalmanFilter *kf, float measured_angle, float measured_omega, float dt) { kf->omega = measured_omega; kf->theta += dt * kf->omega; kf->P[0][0] += dt * (dt * kf->P[1][1] - kf->P[0][1] - kf->P[1][0] + kf->Q_angle); kf->P[0][1] -= dt * kf->P[1][1]; kf->P[1][0] -= dt * kf->P[1][1]; kf->P[1][1] += kf->Q_gyro * dt; float y = measured_angle - kf->theta; float S = kf->P[0][0] + kf->R_angle; float K0 = kf->P[0][0] / S; float K1 = kf->P[1][0] / S; kf->theta += K0 * y; kf->omega += K1 * y; kf->P[0][0] -= K0 * kf->P[0][0]; kf->P[0][1] -= K0 * kf->P[0][1]; kf->P[1][0] -= K1 * kf->P[0][0]; kf->P[1][1] -= K1 * kf->P[0][1]; return kf->theta; #include "kalman_filter.h" void KalmanFilter_Init(KalmanFilter *kf, float Q_angle, float Q_gyro, float R_angle) { kf->theta = 0.0f; kf->omega = 0.0f; kf->P[0][0] = 1.0f; kf->P[0][1] = 0.0f; kf->P[1][0] = 0.0f; kf->P[1][1] = 1.0f; kf->Q_angle = Q_angle; kf->Q_gyro = Q_gyro; kf->R_angle = R_angle; } float KalmanFilter_Update(KalmanFilter *kf, float measured_angle, float measured_omega, float dt) { kf->omega = measured_omega; kf->theta += dt * kf->omega; kf->P[0][0] += dt * (dt * kf->P[1][1] - kf->P[0][1] - kf->P[1][0] + kf->Q_angle); kf->P[0][1] -= dt * kf->P[1][1]; kf->P[1][0] -= dt * kf->P[1][1]; kf->P[1][1] += kf->Q_gyro * dt; float y = measured_angle - kf->theta; float S = kf->P[0][0] + kf->R_angle; float K0 = kf->P[0][0] / S; float K1 = kf->P[1][0] / S; kf->theta += K0 * y; kf->omega += K1 * y; kf->P[0][0] -= K0 * kf->P[0][0]; kf->P[0][1] -= K0 * kf->P[0][1]; kf->P[1][0] -= K1 * kf->P[0][0]; kf->P[1][1] -= K1 * kf->P[0][1]; return kf->theta; } ulartrasonic.c #include "ultrasonic.h" #include "main.h" #include <math.h> #define TRIG_PORT GPIOB #define ECHO_PORT GPIOB #define TRIG_LEFT_PIN GPIO_PIN_2 #define ECHO_LEFT_PIN GPIO_PIN_3 #define TRIG_RIGHT_PIN GPIO_PIN_4 #define ECHO_RIGHT_PIN GPIO_PIN_5 static uint32_t get_pulse_width(GPIO_TypeDef *port, uint16_t pin) { uint32_t start = 0, end = 0; HAL_GPIO_WritePin(TRIG_PORT, TRIG_LEFT_PIN, GPIO_PIN_SET); HAL_Delay(1); HAL_GPIO_WritePin(TRIG_PORT, TRIG_LEFT_PIN, GPIO_PIN_RESET); while (!HAL_GPIO_ReadPin(port, pin)) { start = HAL_GetTick(); if (start > 100) break; } while (HAL_GPIO_ReadPin(port, pin)) { end = HAL_GetTick(); if (end - start > 30) break; } return end - start; } float Get_Left_Distance(void) { uint32_t width = get_pulse_width(ECHO_PORT, ECHO_LEFT_PIN); return width * 0.034 / 2; } float Get_Right_Distance(void) { uint32_t width = get_pulse_width(ECHO_PORT, ECHO_RIGHT_PIN); return width * 0.034 / 2; } pid.c #include "pid.h" void PID_Init(PID_Controller *pid, float Kp, float Ki, float Kd) { pid->Kp = Kp; pid->Ki = Ki; pid->Kd = Kd; pid->integral = 0.0f; pid->last_error = 0.0f; } float PID_Update(PID_Controller *pid, float error, float dt) { pid->integral += error * dt; float derivative = (error - pid->last_error) / dt; float output = pid->Kp * error + pid->Ki * pid->integral + pid->Kd * derivative; pid->last_error = error; return output; } motor.c #include "motor.h" #include "main.h" #include "tim.h" void Motor_SetSpeed(float left, float right) { __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, (uint32_t)left); __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2, (uint32_t)right); } void Motor_Stop(void) { __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 0); __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2, 0); } usart.c /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file usart.c * @brief This file provides code for the configuration * of the USART instances. ****************************************************************************** * @attention * * Copyright (c) 2025 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "usart.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ UART_HandleTypeDef huart1; /* USART1 init function */ void MX_USART1_UART_Init(void) { /* USER CODE BEGIN USART1_Init 0 */ /* USER CODE END USART1_Init 0 */ /* USER CODE BEGIN USART1_Init 1 */ /* USER CODE END USART1_Init 1 */ 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(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART1 interrupt Init */ HAL_NVIC_SetPriority(USART1_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) { if(uartHandle->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USART1 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ void Send_Debug_Info(void) { char buffer[100]; sprintf(buffer, "Left: %.2f cm, Right: %.2f cm\r\n", Get_Left_Distance(), Get_Right_Distance()); HAL_UART_Transmit(&huart1, (uint8_t*)buffer, strlen(buffer), HAL_MAX_DELAY); } /* USER CODE END 1 */ gpio.c /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file gpio.c * @brief This file provides code for the configuration * of all used GPIO pins. ****************************************************************************** * @attention * * Copyright (c) 2025 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "gpio.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /*----------------------------------------------------------------------------*/ /* Configure GPIO */ /*----------------------------------------------------------------------------*/ /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOB, GPIO_PIN_2|GPIO_PIN_4, GPIO_PIN_RESET); /*Configure GPIO pins : PB2 PB4 */ GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_4 | GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : PB3 PB5 */ GPIO_InitStruct.Pin = GPIO_PIN_3|GPIO_PIN_5; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); } /* USER CODE BEGIN 2 */ motion.c#include "motion.h" #include "main.h" #include "main.h" #include <stdio.h> void Motor_SetDirection(int left_forward, int right_forward) { // ×óµç»ú·½Ïò¿ØÖÆ(PB12 PB13) HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, left_forward ? GPIO_PIN_SET : GPIO_PIN_RESET); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_13, left_forward ? GPIO_PIN_RESET : GPIO_PIN_SET); // ÓÒµç»ú·½Ïò¿ØÖÆ(PB14 PB15) HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, right_forward ? GPIO_PIN_SET : GPIO_PIN_RESET); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_15, right_forward ? GPIO_PIN_RESET : GPIO_PIN_SET); } void Move_Forward(float cm) { //ʵÏÖǰ½øÂß¼­ Motor_SetDirection(1, 1); // ×óÓÒµç»úÕýת printf("Moving forward %.1f cm\n", cm); HAL_Delay(500); } void Turn_Left(float angle) { // ʵÏÖ×óתÂß¼­ Motor_SetDirection(0, 1); // ×óµç»ú·´×ª£¬ÓÒµç»úÕýת printf("Turning left %.1f degrees\n", angle); HAL_Delay(500); } void Turn_Right(float angle) { //ʵÏÖÓÒתÂß¼­ Motor_SetDirection(1, 0); // ×óµç»úÕýת£¬ÓÒµç»ú·´×ª printf("Turning right %.1f degrees\n", angle); HAL_Delay(500); }
最新发布
08-01
/* 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 "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "stdio.h" #include "time.h" #include "stdlib.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 */ /* 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 */ int num_tim1; float distance; int first; void Motor_PWM_Start(void) { //PB6 HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_1); //PB7 HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_2); } void SR04_Work(void) { //PA15 HAL_GPIO_WritePin(GPIOA,GPIO_PIN_15,1); HAL_Delay(1); HAL_GPIO_WritePin(GPIOA,GPIO_PIN_15,0); HAL_Delay(60); } void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { if(GPIO_Pin == GPIO_PIN_12) { if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_12)==1) { HAL_TIM_Base_Start(&htim1); __HAL_TIM_SET_COUNTER(&htim1,0); } else if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_12)==0) { HAL_TIM_Base_Stop(&htim1); num_tim1 = __HAL_TIM_GET_COUNTER(&htim1); distance=(float)num_tim1 * 340 / 2 * 100 * 0.000001; } } } int fputc(int ch, FILE* stream) { HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 5); return ch; } void Car_Straight(int speed) { //left reversal //PB7(PWMA),PB8(AIN1),PB9(AIN2):101 HAL_GPIO_WritePin(GPIOB,GPIO_PIN_8,0); HAL_GPIO_WritePin(GPIOB,GPIO_PIN_9,1); __HAL_TIM_SET_COMPARE(&htim4,TIM_CHANNEL_2,speed); //right reversal //PB6(PWMB),PB5(BIN1),PB4(BIN2):101 HAL_GPIO_WritePin(GPIOB,GPIO_PIN_5,0); HAL_GPIO_WritePin(GPIOB,GPIO_PIN_4,1); __HAL_TIM_SET_COMPARE(&htim4,TIM_CHANNEL_1,speed); } //back void Car_Back(int speed) { // PB7(PWMA),PB8(AIN1),PB9(AIN2):110 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, 1); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, speed); // PB6(PWMB),PB5(BIN1),PB4(BIN2):110 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, 1); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, speed); } //turn right void Car_Right(int speed) { // PB7(PWMA),PB8(AIN1),PB9(AIN2):101 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 1); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, speed); // PB6(PWMB),PB5(BIN1),PB4(BIN2):110 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, 1); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, speed); } //turn left void Car_Left(int speed) { // PB7(PWMA),PB8(AIN1),PB9(AIN2):110 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, 1); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, speed); // PB6(PWMB),PB5(BIN1),PB4(BIN2):101 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, 1); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, speed); } //stop void Car_Stop(void) { // PB7(PWMA),PB8(AIN1),PB9(AIN2):000 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, 0); // PB6(PWMB),PB5(BIN1),PB4(BIN2):000 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, 0); } // S void Car_Curve(int speed) { HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 1); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, speed * 0.5); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, 1); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, speed); HAL_Delay(1800); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, 0); HAL_Delay(500); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 1); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, speed); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, 1); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, speed * 0.5); HAL_Delay(1800); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, 0); HAL_Delay(500); // PB7(PWMA),PB8(AIN1),PB9(AIN2):110 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, 1); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, speed); // PB6(PWMB),PB5(BIN1),PB4(BIN2):110 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, 1); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, speed*0.5); HAL_Delay(1800); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, 0); HAL_Delay(500); // PB7(PWMA),PB8(AIN1),PB9(AIN2):110 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, 1); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_2, speed*0.5); // PB6(PWMB),PB5(BIN1),PB4(BIN2):110 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, 1); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, 0); __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, speed); HAL_Delay(1800); } void SG90_Control(int angle) { int value_compare=0; value_compare=11*angle+500; __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_4,value_compare); } /* 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_TIM4_Init(); MX_TIM1_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ Motor_PWM_Start(); srand(HAL_GetTick()); HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_4); SG90_Control(90); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { // 1. ?? 2s(????? 500) SG90_Control(10); HAL_Delay(500); SG90_Control(45); HAL_Delay(500); SG90_Control(90); HAL_Delay(500); SG90_Control(135); HAL_Delay(500); SG90_Control(180); HAL_Delay(500); SR04_Work(); printf("num=%d\n",num_tim1); printf("distance=%.2f\n",distance); HAL_Delay(1000); int turn = rand() % 2; SR04_Work(); HAL_Delay(50); if(first==0) { first++; continue; } if (distance >= 40.0f) { Car_Straight(400); } else { Car_Stop(); HAL_Delay(200); Car_Back(400); HAL_Delay(300); Car_Stop(); HAL_Delay(200); if(!turn) { Car_Left(400); } else { Car_Right(400); } HAL_Delay(400); Car_Stop(); HAL_Delay(200); } HAL_Delay(100); } /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16; 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_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != 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****/ 实现超声波+舵机+电机驱动,实现综合避障,在原有代码基础上,修改代码
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值