/* p5_8.c TIM3 Measuring Period and Frequency * This program configures TIM14 CH1 to toggle PA7 (PWM/D11) * The TIM3 CH1 is set to do Input Capture from PB4 (D5). The program * waits for capture flag (CC1IF) to set then calculates the period and * frequency of the input signal. * A jumper should be used to connect PA7 (D11) to PB4 (D5). * * This program was tested with Keil uVision v5.23 with DFP v2.0.0 */ #include "stm32f0xx.h" ¬¬ unsigned short period[8]; float frequency[8]; int i; int main(void) { unsigned short last = 0; unsigned short current; // configure PA7 as output of TIM14 CH1 RCC->AHBENR |= 0X00020000; /* enable GPIOA clock */ GPIOA->MODER &= ~0x0000C000; /* clear pin mode */ GPIOA->MODER |= 0x00008000; /* set pin to alternate function */ GPIOA->AFR[0] &= ~0xF0000000; /* clear pin AF bits */ GPIOA->AFR[0] |= 0x40000000; /* set pin to AF1 for TIM14 CH1 */ // configure TIM14 to wrap around at 3.33 Hz // and toggle CH1 output when the counter value is 0 RCC->APB1ENR |= 0x00000100; /* enable TIM14 clock */ TIM14->PSC = 800 - 1; /* divided by 800 */ TIM14->ARR = 3000 - 1; /* divided by 3000 */ TIM14->CCMR1 = 0x30; /* set output to toggle on match */ TIM14->CCR1 = 0; /* set match value */ TIM14->CCER |= 1; /* enable ch 1 compare mode */ TIM14->CNT = 0; /* clear counter */ TIM14->CR1 = 1; /* enable TIM14 */ // configure PB4 as input of TIM3 CH1 RCC->AHBENR |= 0x00040000; /* enable GPIOB clock */ GPIOB->MODER &= ~0x00000300; /* clear pin mode */ GPIOB->MODER |= 0x00000200; /* set pin to alternate function */ GPIOB->AFR[0] &= ~0x000F0000; /* clear pin AF bits */ GPIOB->AFR[0] |= 0x00010000; /* set pin to AF1 for TIM3 CH1 */ // configure TIM3 to do input capture with prescaler ... RCC->APB1ENR |= 0x00000002; /* enable TIM3 clock */ TIM3->PSC = 8000 - 1; /* divided by 8000 */ TIM3->CCMR1 = 0x41; /* set CH1 to capture at every edge */ TIM3->CCER = 0x0B; /* enable CH 1 capture both edges */ TIM3->CR1 = 1; /* enable TIM3 */ while (1) { for (i = 0; i < 8; i++) { while (!(TIM3->SR & 0x2)) {} /* wait until input edge is captured */ current = TIM3->CCR1; /* read captured counter value */ period[i] = current - last; /* calculate the period */ last = current; frequency[i] = 1000.0f / period[i]; } __NOP(); /* for setting breakpoint after 8 iterations */ } }