Brian Silverman | 0bca3ba | 2014-03-26 14:07:55 -0700 | [diff] [blame^] | 1 | #ifndef CAPE_TIMER_H_ |
| 2 | #define CAPE_TIMER_H_ |
| 3 | |
| 4 | #include <STM32F2XX.h> |
| 5 | |
| 6 | // inverted is 1 for timing low periods, 0 for high ones. |
| 7 | #define timer_declare(timer, irq, input, inverted, name) \ |
| 8 | static volatile uint32_t name##_length; \ |
| 9 | void irq(void) { \ |
| 10 | timer->SR = ~TIM_SR_CC##input##IF; \ |
| 11 | const uint32_t ccer = timer->CCER; \ |
| 12 | timer->CCER = ccer ^ (TIM_CCER_CC##input##P | TIM_CCER_CC##input##NP); \ |
| 13 | const uint32_t rising = ccer & TIM_CCER_CC##input##P; \ |
| 14 | if (inverted ? rising : !rising) { \ |
| 15 | name##_length = timer->CCR##input; \ |
| 16 | } else { \ |
| 17 | timer->EGR = TIM_EGR_UG; \ |
| 18 | } \ |
| 19 | } |
| 20 | |
| 21 | // You need to enable the clock, set up the alt function for the input pin, |
| 22 | // set the prescaler, and set up the timer input before calling this. |
| 23 | #define timer_setup(timer, irq, input) \ |
| 24 | do { \ |
| 25 | timer->CR1 = TIM_CR1_URS; \ |
| 26 | timer->DIER = TIM_DIER_CC##input##IE; \ |
| 27 | timer->CCER = TIM_CCER_CC##input##P | TIM_CCER_CC##input##E; \ |
| 28 | timer->EGR = TIM_EGR_UG; \ |
| 29 | timer->CR1 |= TIM_CR1_CEN; \ |
| 30 | NVIC_SetPriority(irq, 1); \ |
| 31 | NVIC_EnableIRQ(irq); \ |
| 32 | } while (0) |
| 33 | |
| 34 | #endif // CAPE_TIMER_H_ |