I will not particularly go into the theory, there are many resources in the network where everything is described in great detail. But when it comes to practice, you understand that everything is much more complicated. Used microcontroller stm32l152c-discovery. The article will describe the process of starting the PWM of two timers at the same time (full synchronization):
As well as the launch with a lag (in the photo the lag in the floor of the period)
Create a function for initPWM initialization, declare variables for convenience
void initPWM() { const uint32_t Period = 20 - 1;
First you need to initialize the structures to configure the timers:
GPIO_InitTypeDef port; TIM_TimeBaseInitTypeDef timer; TIM_OCInitTypeDef timerPWM;
Next, we activate the necessary peripherals. We will use TIM3 and TIM4, simply because it wanted to:
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
GPIOB activate, because Timer outputs sit on this PB5 and PB9 bus. This information can be found in the user manual for the microcontroller in the table MCU pin description versus board function.
We configure the outputs in the alternative function mode:
GPIO_StructInit(&port); port.GPIO_Mode = GPIO_Mode_AF;
Configuring the timer in the PWM mode:
TIM_TimeBaseStructInit(&timer); timer.TIM_ClockDivision = TIM_CKD_DIV1; timer.TIM_CounterMode = TIM_CounterMode_Up;
We initialize the necessary channels for timers, we look for channels in the user manual:
TIM_OC2Init(TIM3, &timerPWM); TIM_OC4Init(TIM4, &timerPWM);
And now the most important is the synchronization setting. It is necessary to make one timer master, another slave:
If we need to make a backlog, let's say for the half of the period, then we need to set the initial value of the sub-timer count equal to half the period. For full synchronization, we start the account from 0:
TIM_SetCounter(TIM3, 10);
Activate the timers:
TIM_Cmd(TIM3, ENABLE);
I post the whole code in full:
#include "stm32l1xx.h"
That's all. In my task, it was necessary to control two stepper motors. Additionally, the code for smooth overclocking was written, it began work with a longer period and gradually reduced it with the TIM_SetAutoreload function.