/* p5_7.c TIM3 Input Capture * * This program configures TIM3 CH2 to toggle PC7 as was done in p5_6. * * The TIM17 CH1 is set to do Input Capture from PA7 (D11). The program * waits for capture flag (CC1IF) to set then stores the captured value * in a global variable to be watched by the debugger. The flag is * cleared by reading CCR1. * A jumper should be used to connect PC7 (D9) to PA7 (D11). * * This program was tested with Keil uVision v5.23 with DFP v2.0.0 */ #include "stm32f0xx.h" unsigned short timestamp[8]; int i; int main(void) { // configure PC7 as output of TIM3 CH2 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 = 800 - 1; /* divided by 800 */ TIM3->ARR = 10000 - 1; /* divided by 10000 */ TIM3->CCMR1 = 0x3000; /* set output to toggle on match */ TIM3->CCR2 = 0; /* set match value */ TIM3->CCER |= 0x10; /* enable CH2 compare mode */ TIM3->CNT = 0; /* clear counter */ TIM3->CR1 = 1; /* enable TIM3 */ // configure PA7 as input of TIM17 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] |= 0x50000000; /* set pin to AF5 for TIM17 CH1 */ // configure TIM17 to do input capture with prescaler ... RCC->APB2ENR |= 0x00040000; /* enable TIM17 clock */ TIM17->PSC = 8000 - 1; /* divided by 8000 */ TIM17->CCMR1 = 0x41; /* set CH1 to input */ TIM17->CCER = 1; /* enable CH 1 capture on the rising edge */ TIM17->CR1 = 1; /* enable TIM3 */ while (1) { for (i = 0; i < 8; i++) { while (!(TIM17->SR & 2)) {} /* wait until input edge is captured */ timestamp[i] = TIM17->CCR1; /* read captured counter value */ } __NOP(); /* for setting breakpoint after 8 iterations */ } }