STM32 ONE PULSE MODE.
In one of my projects I used the following mechanism to control a buzzer: I turned it on manually, started a timer and turned it off in the interrupt triggered by the timer overflow. Over time the number of interrupts in the project grew, and other interrupts often prevented the one that turned off the buzzer from firing. As a result, the buzzer always produced a beep of varying length. To solve this problem, I had to abandon the interrupt and generate a pulse of a fixed length in hardware. Below is the code that does this.
The number of pulses can be changed, for example by setting it to 5.
//Enable clocking for GPIOA_2 and TIM15
RCC->AHBENR |= RCC_AHBENR_GPIOAEN;
RCC->APB2ENR |= RCC_APB2ENR_TIM15EN;
//PA2 push-pull alternate function
GPIOA->MODER |= GPIO_MODER_MODER2_1;
GPIOA->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR2;
GPIOA->PUPDR &= ~GPIO_PUPDR_PUPDR2;
GPIOA->AFR[0] |= (0x09<<2*4);//TIM15_CH1
TIM15->PSC = 7200 -1; //timer frequency 10kHz
TIM15->ARR = 350 - 1; //reload value
TIM15->CCR1 = 35;// pulse length
TIM15->RCR = 1 - 1; //number of repetitions
TIM15->EGR = TIM_EGR_UG; //required to load the prescaler
TIM15->CR1 &= ~TIM_CR1_DIR; //count up
TIM15->CR1 |= TIM_CR1_OPM; //the counter stops after counting up to arr
TIM15->CCMR1 = TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1PE;// select PWM mode and enable preload
TIM15->SMCR = RESET; //clock from the internal source
TIM15->CCER |= TIM_CCER_CC1E;/ / enable Compare output channel 1
TIM15->BDTR |= TIM_BDTR_MOE;//allow the timer pins to be used as outputs
TIM15->CR1 |= TIM_CR1_CEN;//start the timer
The number of pulses can be changed, for example by setting it to 5.
