pulse counter stm32

Dependencies:   mbed

Committer:
c128
Date:
Wed Oct 07 05:50:07 2015 +0000
Revision:
2:6f1807a35656
Parent:
1:3d22d4e6de38
Child:
3:8c3e5f30cb6d
easy example counter up/down direction and steps for stepper motor

Who changed what in which revision?

UserRevisionLine numberNew contents of line
c128 2:6f1807a35656 1
c128 0:6adab3889554 2 #include "mbed.h"
c128 0:6adab3889554 3 #include "stm32f4xx.h"
c128 2:6f1807a35656 4 #include "stm32f4xx_hal_tim_ex.h"
c128 2:6f1807a35656 5
c128 2:6f1807a35656 6 TIM_HandleTypeDef timer;
c128 2:6f1807a35656 7 TIM_Encoder_InitTypeDef encoder;
c128 2:6f1807a35656 8
c128 2:6f1807a35656 9 //direction to PA_9 -- step to PA_8
c128 0:6adab3889554 10
c128 0:6adab3889554 11 int main(){
c128 2:6f1807a35656 12 GPIO_InitTypeDef GPIO_InitStruct;
c128 2:6f1807a35656 13 __TIM1_CLK_ENABLE();
c128 2:6f1807a35656 14 __GPIOA_CLK_ENABLE();
c128 2:6f1807a35656 15 GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9;
c128 2:6f1807a35656 16 GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
c128 2:6f1807a35656 17 GPIO_InitStruct.Pull = GPIO_PULLDOWN;
c128 2:6f1807a35656 18 GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
c128 2:6f1807a35656 19 GPIO_InitStruct.Alternate = GPIO_AF1_TIM1;
c128 2:6f1807a35656 20 HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
c128 2:6f1807a35656 21
c128 2:6f1807a35656 22 timer.Instance = TIM1;
c128 2:6f1807a35656 23 timer.Init.Period = 0xffff;
c128 2:6f1807a35656 24 timer.Init.Prescaler = 1;
c128 2:6f1807a35656 25 timer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
c128 2:6f1807a35656 26 timer.Init.CounterMode = TIM_COUNTERMODE_UP;
c128 2:6f1807a35656 27
c128 2:6f1807a35656 28 HAL_TIM_Base_Init(&timer);
c128 2:6f1807a35656 29
c128 2:6f1807a35656 30 encoder.EncoderMode = TIM_ENCODERMODE_TI1;
c128 2:6f1807a35656 31 encoder.IC1Filter = 0x0f;
c128 2:6f1807a35656 32 encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING; //step signal
c128 2:6f1807a35656 33 encoder.IC1Prescaler = TIM_ICPSC_DIV1;
c128 2:6f1807a35656 34 encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;
c128 0:6adab3889554 35
c128 2:6f1807a35656 36 encoder.IC2Filter = 0x0f;
c128 2:6f1807a35656 37 encoder.IC2Polarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE; //check direction
c128 2:6f1807a35656 38 encoder.IC2Prescaler = TIM_ICPSC_DIV1;
c128 2:6f1807a35656 39 encoder.IC2Selection = TIM_ICSELECTION_INDIRECTTI;
c128 2:6f1807a35656 40
c128 2:6f1807a35656 41 HAL_TIM_Encoder_Init(&timer, &encoder);
c128 2:6f1807a35656 42 HAL_TIM_Encoder_Start(&timer,TIM_CHANNEL_1);
c128 2:6f1807a35656 43
c128 2:6f1807a35656 44
c128 2:6f1807a35656 45 TIM1->EGR = 1; // Generate an update event
c128 2:6f1807a35656 46 TIM1->CR1 = 1; // Enable the counter
c128 2:6f1807a35656 47
c128 0:6adab3889554 48
c128 0:6adab3889554 49 while (1) {
c128 0:6adab3889554 50 int16_t count1;
c128 2:6f1807a35656 51 count1=TIM1->CNT;
c128 0:6adab3889554 52
c128 0:6adab3889554 53 printf("%d\r\n", count1);
c128 0:6adab3889554 54 wait(1.0);
c128 2:6f1807a35656 55
c128 0:6adab3889554 56 };
c128 0:6adab3889554 57 }