/* p6_6.c Timer TIM3 interrupt * * Timer TIM3 is configured as an up-counter. By default, the system clock is * running at 8 MHz. The prescaler is set to divide by 8,000 that gives a * 1 kHz clock to the counter. * The timer is set up for output compare interrupt for channel 2. When the * counter matches the CCR2 register, the output toggles and an interrupt * is triggered. In the interrupt handler, the PERIOR value is added CCR2 * so that the next CCR2 match occurs after the PERIOR count. * When the PERIOD is set to 1000, the output toggles at 1 Hz. * The output of TIM3 Channel 1 is PC7 (PWM/D9). * * This program was tested with Keil uVision v5.23 with DFP v2.0.0 */ #include "stm32f0xx.h" #define PERIOD 1000 void delayMs(int n); int main(void) { __disable_irq(); /* global disable IRQs */ // Configure PC7 as TIM3_CH2 output to drive the LED RCC->AHBENR |= 0x00080000; /* enable GPIOC clock */ GPIOC->MODER &= ~0x0000C000; /* clear pin mode */ GPIOC->MODER |= 0x00008000; /* set pin to alternate function */ GPIOC->AFR[0] &= 0xF0000000; /* clear pin AF bits to set pin to AF0 for TIM3 CH2 */ // configure TIM3 to wrap around at 1 Hz // and toggle CH2 output when the counter value is 0 RCC->APB1ENR |= 0x00000002; /* enable TIM3 clock */ TIM3->PSC = 8000 - 1; /* divided by 8000 */ TIM3->ARR = 0xFFFF; /* set to max value */ TIM3->CCMR1 = 0x3000; /* set output to toggle on match */ TIM3->CCR2 = PERIOD; /* set match value */ TIM3->CCER |= 0x10; /* enable CH2 compare mode */ TIM3->CNT = 0; /* clear counter */ TIM3->CR1 = 1; /* enable TIM3 */ TIM3->SR = 0; /* clear UIF */ TIM3->DIER |= 0x00000004; /* enable CC2IE */ NVIC_EnableIRQ(TIM3_IRQn); /* enable interrupt in NVIC */ __enable_irq(); /* global enable IRQs */ while (1) { } } void TIM3_IRQHandler(void) { TIM3->SR = 0; /* clear UIF */ TIM3->CCR2 = TIM3->CCR2 + PERIOD; /* update CCR2 */ }