Currently viewing the tag: "encoder"

Well, I must admit I am impressed with the motor control capability of the STM32 series; within a couple of hours of coding I have got complementary PWM working, and the quadrature encoders hooked up to one of the timers. The one gripe I have so far is the difficulty in getting documentation to do a specific task, for motor control this is king:

AN4013, timer overview

Code examples of the PWM with complementary outputs can be found in the .ProjectSTM32F4xx_StdPeriph_Examples folder of the STM32F4xx_DSP_StdPeriph_Lib_V1.0.1 library.

The encoder is not covered, but its pretty simple.

Put this at the top

#include "stm32f4xx_tim.h"

Then set up the GPIO so that the two encoder inputs are enabled and set as alternate function mode, and connect them to the timer (using timer 4 in this example):

	/* GPIOA Peripheral clock enable */
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);

	/* AF Mode for peripherals - PORTB */
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	/* Connect TIM pins to AF */
	GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_TIM4);
	GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_TIM4);

Now set up the timer – using the API

	/* TIM4 clock enable */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

	/* Configure the timer */
	TIM_EncoderInterfaceConfig(TIM4, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);

	/* TIM4 counter enable */
	TIM_Cmd(TIM4, ENABLE);

Now its all running, the timer 4 counter will increase / decrease with the direction bit set too.

Tagged with: