1.1K
#include "main.h" #include"stdio.h" ADC_HandleTypeDef hadc1; TIM_HandleTypeDef htim2; UART_HandleTypeDef huart1; void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_TIM2_Init(void); static void MX_ADC1_Init(void); static void MX_USART1_UART_Init(void); int main(void) { /* USER CODE BEGIN 1 */ uint16_t readValue; int speed; char str[20]; /* USER CODE END 1 */ HAL_Init(); MX_GPIO_Init(); MX_TIM2_Init(); MX_ADC1_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ HAL_ADC_Start(&hadc1); //PB1 HAL_TIM_Base_Start(&htim2); //Initialize stm32 timer 3 HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_3); //Start pwm second motor 100% duty cycle /* USER CODE END 2 */ while (1) { switch(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_6)) { case GPIO_PIN_SET: // L298 Drive Motor HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_4); HAL_ADC_PollForConversion(&hadc1,1000); readValue = HAL_ADC_GetValue(&hadc1); readValue = (readValue<<4); sprintf(str,"ADC value = %u ", readValue); HAL_UART_Transmit(&huart1,(uint8_t*)str, sizeof(str),100); HAL_UART_Transmit(&huart1,(uint8_t*)&"\n\r",2,2); HAL_Delay(200); if (readValue < 1872) { HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_15, 1); speed = (readValue - 1800) * (-1) ; } else if (readValue > 1900) { HAL_GPIO_WritePin(GPIOB, GPIO_PIN_15, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, 1); speed = (readValue - 1800) ; } else { speed = 0; } __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_4, speed); HAL_Delay(50); break; case GPIO_PIN_RESET: // L293D Drive Motor //STOP L298 Drive Motor HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, 0); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_15, 0); if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_6)==GPIO_PIN_RESET) { HAL_GPIO_WritePin(GPIOB,GPIO_PIN_12,0); HAL_GPIO_WritePin(GPIOB,GPIO_PIN_13,0); HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14,0); HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15,0); } //Clockwise if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_7)==GPIO_PIN_RESET) { HAL_GPIO_WritePin(GPIOB,GPIO_PIN_12,1); HAL_GPIO_WritePin(GPIOB,GPIO_PIN_13,0); } //AntiClockwise if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_8)==GPIO_PIN_RESET) { HAL_GPIO_WritePin(GPIOB,GPIO_PIN_12,0); HAL_GPIO_WritePin(GPIOB,GPIO_PIN_13,1); } //Motor rotate at 25% duty cycle if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_9)==GPIO_PIN_RESET) { __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,25); //Second motor 25% voltage } //Motor rotate at 50% duty cycle if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_10)==GPIO_PIN_RESET) { __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,50); //Second motor 50% voltage } //Motor rotate at 75% duty cycle if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_11)==GPIO_PIN_RESET) { __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,75); //Second motor 75% voltage } break; default: // Handle any unexpected cases break; } } }