2018-06-19 09:29 AM
I am trying to configure the TIM2 to act as an up/down counter as describe in Encoder mode 1 or 2. I have the circuit set up to connect PB8 to a count signal and PB9 as a direction signal. I have am having an issue where randomly after an NVIC_Reset the count direction is different dispite the value on PB9 being the same. The itnitialization code is below:
void initializeStepDir()
{
TIM_HandleTypeDef timer;
TIM_Encoder_InitTypeDef encoder;
// Enable syscfg clock
RCC->APB2ENR |= (RCC_APB2ENR_SYSCFGEN);
// Reset the TIM2 block
RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST);
RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST);
// Enable the TIM2 block
RCC->APB1ENR |= (RCC_APB1ENR_TIM2EN);
timer.Instance = TIM2;
timer.Init.Period = 0xffffffff;
timer.Init.Prescaler = 1;
timer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
timer.Init.CounterMode = TIM_COUNTERMODE_UP;
constexpr uint32_t FILTER_NUMBER = 3;
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
encoder.IC1Filter = FILTER_NUMBER;
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING; //step signal
encoder.IC1Prescaler = TIM_ICPSC_DIV1;
encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;
encoder.IC2Filter = FILTER_NUMBER;
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_ALL);
// NOTE: TI1 -> PB8 TI2 -> PB9
// https://community.st.com/external-link.jspa?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F32947972%2Fstm32-how-to-make-pulse-count-up-down-with-timer
}�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?
What could cause the system to behave differently given the same inputs? Is this the correct configuration? The stack overflow link in the code suggests that it is for some configuration.
2018-06-19 10:18 AM
What part/board are you using, lets try and scope this a bit more tightly.
Why Prescaler=1 (DIV2)
2018-06-19 11:29 AM
The STM32 timers don't have a 'direction-count' interface/mode, so I wonder how your input signals look like, exactly.
Any 'scope or LA waveforms to show us?
JW
2018-06-19 01:31 PM
Why Prescaler=1 (DIV2)
Well spotted, Clive. In encoder mode, nonzero prescaler has surprising effect (as prescaler is *not* up-down counter).
JW
2018-07-03 12:42 PM
Sorry for the delay in response. The waveforms look like you would expect:
The code above works consistently but at some point the counter starts countingin a random direction at boot.
2018-07-03 12:43 PM
The board is a custom designed board as well.