Electrical – STM32 HAL driver for register value update

chal-librarypwmstm32stm32f4

I am new to HAL drivers and STM32 MCUs. Can anyone tell me how to use HAL drivers to update register values of STM32F407 MCU? I have to programatically update the values of ARR and CCR registers of TIM1 to generate PWM waveforms.

Best Answer

You can configure PWM signals and generate this codes by using prgram interface of CubeMX.
enter image description here

I used Tim4 for generate 1 Hz frequency PWM. My clock Speed on this project 168MHz. it is imported for calculate PWM frequency.

enter image description here

Tim4 depend APB1 Peripheral clock. APB1 Clock frequency is System Clock Frequency / 2. So my clock frequency is 84MHz. I changed presceler value to 42000 and changed my counter periyod to 2000 to set PWM frequency to 1Hz. Because 84MHz/(42k*2k) = 1. Tim1 depend APB2 peripheral clock and this clock frequency is System clock. So when use same values for timer1 its end up 2Hz PWM.

As a result you dont need to change register for generate pwm. You can use cubemx for this. I also share my project main code and github link in order to examine. In my project i use 4 channel of tim4 because i generate 4 different duty cycle values (%25, %50, %75, %100).

  /* USER CODE BEGIN 2 */
/*TIM2 PWM gönderimi için channellar ayarlanir */
HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_2);
HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_3);
HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_4);

/*
Ayarlanmis channellarin duty cycle ayarlari yapilir.
CH1 (D12) için %25
CH2 (D12) için %50
CH3 (D12) için %75
CH4 (D12) için %100
Prescaler = 42000, Counter Period = 2000 toplam çarpimi 84Mhz  dolayisiyla sinyal 1 Hz 
Periyot degerinin duty cyclea göre istedigimiz gibi dagitabiliriz. %25 için 2000*25/100 = 500
*/
__HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_1, 500  - 1);
__HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_2, 1000 - 1);
__HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_3, 1500 - 1);
__HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_4, 2000 - 1);

/* USER CODE END 2 */

https://github.com/Bisbiliroglu/STM32F4_CubeMX_HAL/tree/master/PWM