paolo della vedova
/
stm32_pulse_counter
pulse counter stm32
Diff: counter.cpp
- Revision:
- 2:6f1807a35656
- Parent:
- 1:3d22d4e6de38
- Child:
- 3:8c3e5f30cb6d
--- a/counter.cpp Tue Sep 29 14:10:53 2015 +0000 +++ b/counter.cpp Wed Oct 07 05:50:07 2015 +0000 @@ -1,26 +1,57 @@ -// reference this code http://www.fmf.uni-lj.si/~ponikvar/STM32F407%20project/Timer2_Counting.pdf + #include "mbed.h" #include "stm32f4xx.h" +#include "stm32f4xx_hal_tim_ex.h" + +TIM_HandleTypeDef timer; +TIM_Encoder_InitTypeDef encoder; + +//direction to PA_9 -- step to PA_8 int main(){ - RCC->AHB1ENR |= 0x01 + 0x10; // Clock for PortA, E - RCC->APB1ENR |= 0x01; // Clock for Timer2 - GPIOA->MODER |= 0x00000008; // all inputs but: PA1 => AF mode - GPIOA->AFR[0] |= 0x00000010; // select AF1 (TIM2) for PA01 -> TIM2_CH2 + GPIO_InitTypeDef GPIO_InitStruct; + __TIM1_CLK_ENABLE(); + __GPIOA_CLK_ENABLE(); + GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLDOWN; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF1_TIM1; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + timer.Instance = TIM1; + timer.Init.Period = 0xffff; + timer.Init.Prescaler = 1; + timer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + timer.Init.CounterMode = TIM_COUNTERMODE_UP; + + HAL_TIM_Base_Init(&timer); + + encoder.EncoderMode = TIM_ENCODERMODE_TI1; + encoder.IC1Filter = 0x0f; + encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING; //step signal + encoder.IC1Prescaler = TIM_ICPSC_DIV1; + encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI; - TIM2->CCMR1 |= 0x0100; // Ch. 2 as TI2 - TIM2->SMCR |= 0x0007; // Ext. clk mode 1 - TIM2->SMCR |= 0x0060; // TI2FP2 as ext. clock - TIM2->CR1 |= 0x0001; // enable counting + encoder.IC2Filter = 0x0f; + encoder.IC2Polarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE; //check direction + encoder.IC2Prescaler = TIM_ICPSC_DIV1; + encoder.IC2Selection = TIM_ICSELECTION_INDIRECTTI; + + HAL_TIM_Encoder_Init(&timer, &encoder); + HAL_TIM_Encoder_Start(&timer,TIM_CHANNEL_1); + + + TIM1->EGR = 1; // Generate an update event + TIM1->CR1 = 1; // Enable the counter + while (1) { int16_t count1; - count1=TIM2->CNT; + count1=TIM1->CNT; printf("%d\r\n", count1); wait(1.0); - if (GPIOE->IDR & 0x01) TIM2->CNT = 0; // reset counter - if (GPIOE->IDR & 0x02) TIM2->CR1 |= 0x01; // enable counter - if (GPIOE->IDR & 0x04) TIM2->CR1 &= ~0x01; // disable counter + }; } \ No newline at end of file