1.6K
#include "main.h" /* USER CODE BEGIN PFP */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if(htim == &htim3) { pulseEND = 1 ; } } /* USER CODE END PFP */ /* USER CODE BEGIN 0 */ #define TIMCLOCK 60000000 #define PRESCALAR 60 #define ERRUR 416 // ERRUR Simulation is not running in real time uint32_t IC_Val1 = 0; uint32_t IC_Val2 = 0; uint32_t Difference = 0; uint8_t MSG[50]; int Is_First_Captured = 0; float frequency = 0; void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) { if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4) { if (Is_First_Captured==0) // if the first rising edge is not captured { IC_Val1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_4); // read the first value Is_First_Captured = 1; // set the first captured as true } else // If the first rising edge is captured, now we will capture the second edge { IC_Val2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_4); // read second value if (IC_Val2 > IC_Val1) { Difference = IC_Val2-IC_Val1; } else if (IC_Val1 > IC_Val2) { Difference = (0xffffffff - IC_Val1) + IC_Val2; } float refClock = TIMCLOCK/(PRESCALAR); frequency = refClock/Difference; int x = frequency; x-=ERRUR; sprintf(MSG,"result = %d \n\r",x); HAL_UART_Transmit(&huart1,MSG, sizeof(MSG), 100); __HAL_TIM_SET_COUNTER(htim, 0); // reset the counter Is_First_Captured = 0; // set it back to false } } } /* USER CODE END 0 */ int main(void) { HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_TIM1_Init(); MX_TIM2_Init(); MX_TIM3_Init(); MX_USART1_UART_Init(); while (1) { if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_13)==GPIO_PIN_SET) { HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_3); //start the TIMER 3 in PWM MODE HAL_Delay(1000); //1 second delay TIM3->ARR = 1 ; // signal period of the PWM __HAL_TIM_ENABLE(&htim3); //ENable TIM3 while(!pulseEND){}; pulseEND=0; } else if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_14)==GPIO_PIN_SET) { HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2); //start the TIMER 2 in PWM MODE uint32_t CH1; while (CH1 < 99 ) { TIM2->CCR2 = CH1; CH1+= 1 ; HAL_Delay(1); } while (CH1 > 0 ) { TIM2->CCR2 = CH1; CH1-= 1 ; HAL_Delay(1); } } else if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_15)==GPIO_PIN_SET) { TIM2->CCR3 = 50; //set the PWM duty cycle of TIMER2 to 50% HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_3); //start the PWM signal on TIM2 HAL_TIM_IC_Start_IT(&htim1, TIM_CHANNEL_4);//starts an interrupt input capture } else { HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_2); HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_3); HAL_TIM_PWM_Stop(&htim3, TIM_CHANNEL_2); HAL_TIM_IC_Stop_IT(&htim1, TIM_CHANNEL_4); } } /* USER CODE END 3 */ }