Why the encoder counting down?

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
bittware
Posts: 45
Joined: Mon Aug 18, 2014 3:27 am

Why the encoder counting down?

Post by bittware » Thu Jun 02, 2022 3:12 am

After referring to @dhylands 'example at https://github.com/dhylands/upy-example ... ncoder2.py, I found the prescaler setting does matter and prescaler=0 won't work whatsoever whereas prescaler=1 really works. Why is that?
Additionally, although prescaler=1 makes the encoder mode work, it indeed counts in opposite direction.
For example, if period set to 10000, the counting follows 0->10000->9999->9998 ... ->0->10000->9999, etc.
After trying out all the tweaks that I can imagine, the counting behavior does not change at all?
Is it a bug or something I obviously overlooked?
P.S. I use MicroPython v1.18 on 2022-01-17; PYBv1.1 with STM32F405RG

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Why the encoder counting down?

Post by Roberthh » Thu Jun 02, 2022 5:56 am

If you swap the wires of the encoder, the counting direction will change.

bittware
Posts: 45
Joined: Mon Aug 18, 2014 3:27 am

Re: Why the encoder counting down?

Post by bittware » Thu Jun 02, 2022 6:09 am

Roberthh wrote:
Thu Jun 02, 2022 5:56 am
If you swap the wires of the encoder, the counting direction will change.
Yes, it's true. But why is that?
I tried

Code: Select all

        x_cnt = Pin(Pin.cpu.A1, Pin.AF_PP, pull=Pin.PULL_DOWN, af=Pin.AF2_TIM5)
        x_timer = Timer(5, prescaler=1, period=0x3fffffff)
        x_channel = x_timer.channel(1, Timer.ENC_B)  # The channel number is ignored when setting the encoder mode

        y_cnt = Pin(Pin.cpu.B6, Pin.AF_PP, pull=Pin.PULL_DOWN, af=Pin.AF2_TIM4)
        y_timer = Timer(4, prescaler=1, period=0xffff)
        y_channel = y_timer.channel(1, Timer.ENC_A)
Both counting up by default. What is so special with?

Code: Select all

        z_cnt = Pin('X1', Pin.AF_OD, pull=Pin.PULL_DOWN, af=Pin.AF1_TIM2)
        z_timer = Timer(2, prescaler=1, period=0x3fffffff)
        z_channel = z_timer.channel(1, Timer.ENC_A)
This one counts down by default.

bittware
Posts: 45
Joined: Mon Aug 18, 2014 3:27 am

Re: Why the encoder counting down?

Post by bittware » Thu Jun 02, 2022 7:28 am

I think I've found why.
You need to have the other pin-pair in fixed state to make sure the counting direction is determined.
If so, the other pin-pair needs to be reserved instead of being used for other purpose as it could bring up random state when the counting starts.

Post Reply