#include "stm32c031xx.h"
static void gpio_led_init(void)
{
/* Enable GPIOA clock */
RCC->IOPENR |= RCC_IOPENR_GPIOAEN;
/* PA5 -> output mode */
GPIOA->MODER &= ~(3U << (5U * 2U));
GPIOA->MODER |= (1U << (5U * 2U));
}
static void tim3_init_500ms(void)
{
/* Enable TIM3 clock */
RCC->APBENR1 |= RCC_APBENR1_TIM3EN; //Advanced Peripheral Bus -> APB
/*
Timer clock = 48 MHz
Step 1: Prescaler
48 MHz / 48000 = 1000 Hz
-> 1 tick = 1 ms
*/
TIM3->PSC = 48000 - 1;
/*
Step 2: Auto-reload register
500 ticks × 1 ms = 500 ms
*/
TIM3->ARR = 500 - 1;
/* Reset counter */
TIM3->CNT = 0;
/* Apply registers immediately */
TIM3->EGR |= TIM_EGR_UG; // apply configuration now [applies PSC and ARR immediately]
/* Start timer */
TIM3->CR1 |= TIM_CR1_CEN;
}
int main(void)
{
gpio_led_init();
tim3_init_500ms();
while (1)
{
/* Wait until update event */ // UIF = Update Interrupt Flag
while (!(TIM3->SR & TIM_SR_UIF)); // wait until the timer reaches ARR
// The timer sets this flag when: CNT = ARR
/* Clear update flag */
TIM3->SR &= ~TIM_SR_UIF;
/* Toggle LED */
GPIOA->ODR ^= (1U << 5);
}
}Loading
st-nucleo-c031c6
st-nucleo-c031c6