/* p5_9.c TIM1 External Event Counting * This program configures TIM1 to use external input PA12 as the * counter clock source. Each rising edge of the input signal * increments the TIM1 counter by 1. * Use an external signal to drive PA12 for testing. * Or use a jumper between PC13 and PA12. PC13 is connected to the * user switch of the Nucleo board. * * This program was tested with Keil uVision v5.23 with DFP v2.0.0 */ #include "stm32f0xx.h" int main(void) { unsigned short counter; // configure PA5 output for the LED RCC->AHBENR |= 0X00020000; /* enable GPIOA clock */ GPIOA->MODER &= ~0x00000C00; /* clear pin mode */ GPIOA->MODER |= 0x00000400; /* set pin to output mode */ // configure PA12 as input of TIM1 ETR GPIOA->MODER &= ~0x03000000; /* clear pin mode */ GPIOA->MODER |= 0x02000000; /* set pin to alternate function */ GPIOA->AFR[1] &= ~0x000F0000; /* clear pin AF bits */ GPIOA->AFR[1] |= 0x00020000; /* set pin to AF2 for TIM1 ETR */ // configure TIM1 to use external input as counter clock source RCC->APB2ENR |= 0x00000800; /* enable TIM1 clock */ TIM1->SMCR = 0x4377; /* use ETR input as clock, no prescaler */ TIM1->CNT = 0; /* clear counter */ TIM1->CR1 = 1; /* enable TIM1 */ while (1) { // use bit 0 to turn LED on/off counter = TIM1->CNT; if (counter & 1) GPIOA->ODR |= 0x20; /* turn on LED */ else GPIOA->ODR &= ~0x20; /* turn off LED */ } }