Advertisement
wojiaocbj

timer

Nov 26th, 2022
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. TIM_HandleTypeDef htim2;
  2. void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *phtim){
  3.     if(phtim->Instance == TIM2){
  4.         //do something
  5.     }
  6. }
  7. void TIM2_IRQHandler(){
  8.     HAL_TIM_IRQHandler(&htim2);
  9.  
  10. }
  11. void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *phtim){
  12.     if(phtim->Instance == TIM2){
  13.         __HAL_RCC_TIM2_CLK_ENABLE();
  14.         HAL_NVIC_SetPriority(TIM2_IRQn, 2, 0);
  15.         HAL_NVIC_EnableIRQ(TIM2_IRQn);
  16.     }
  17. }
  18. void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *phtim){
  19.     if(phtim->Instance == TIM2){
  20.         __HAL_RCC_TIM2_CLK_ENABLE();
  21.     }
  22. }
  23. void tim2_init_interrupt(unsigned short autoreload, unsigned short prescaler){
  24.  
  25.     htim2.Instance = TIM2;
  26.     htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  27.     htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  28.     htim2.Init.Period = autoreload;
  29.     htim2.Init.Prescaler = prescaler;
  30.     HAL_TIM_Base_Init(&htim2);
  31.  
  32. }
  33. void tim2_init_pwm_ch4(unsigned short autoreload, unsigned short prescaler){
  34.     GPIO_InitTypeDef gpio;
  35.     TIM_OC_InitTypeDef timoc;
  36.     htim2.Instance = TIM2;
  37.     htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  38.     htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  39.     htim2.Init.Period = autoreload;
  40.     htim2.Init.Prescaler = prescaler;
  41.     HAL_TIM_PWM_Init(&htim2);
  42.     timoc.OCMode = TIM_OCMODE_PWM1;
  43.     timoc.Pulse = autoreload / 2;
  44.     timoc.OCPolarity = TIM_OCPOLARITY_LOW;
  45.     gpio.Mode = GPIO_MODE_AF_PP;
  46.     gpio.Pull = GPIO_PULLUP;
  47.     gpio.Speed = GPIO_SPEED_HIGH;
  48.     gpio.Alternate = GPIO_AF1_TIM2;
  49.     gpio.Pin = GPIO_PIN_11;
  50.     HAL_GPIO_Init(GPIOB, &gpio);
  51.     HAL_TIM_PWM_ConfigChannel(&htim2, &timoc, TIM_CHANNEL_4);
  52. }
  53. void tim2_pwmch4_setcompare(unsigned short cmpval){
  54.     htim2.Instance->CCR4 = cmpval;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement