LennartHennigs / ESPRotary

Arduino/ESP library to simplify reading rotary encoder data.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Example code does not appear to run on an Arduino Mega 2560

Win-doze opened this issue · comments

Thanks for providing this library. I am trying to run your example SimpleCounterWithButton, but for the life of me I cannot get any output from the encoder. The button works in the sketch as expected. The only changes I made were the to remove D from each of the pin numbers. I know the encoder is working as I can swap the wires from that individually to the button input and cause the rotation to generate 'click' and 'reset' messages. I have also tinkered with the pin numbers to check I don't have a faulty MCU.
In desperation I tried the code on an uno which was working with a different library and that failed too.
Can you offer any guidance?

Just working on from this, I can see that this line of the code never tests true in 'void ESPRotary::loop()'
if (getPosition() >= lower_bound && getPosition() <= upper_bound) {
Commenting out the line gets a callback response.
The result of getPosition() is position/steps_per_click, So if steps_per_click is other than 1 you could have 'position' outside the upper or lower bounds and still in theory pass the test.
Replacing 'getPosition' with 'position' in the if statement still fails for some reason, I'm not sure if it has something to do with the scope of the variable.
Finally resetPosition function may have an error, if last_position is ever set to 'lower_bound * steps_per_click' then position is set to 'lower_bound * steps_per_click * steps_per_click'.

I have found one of the errors.
Default lower_bound and upper_bound are -32768/32768 but with a 16bits signed int the bound should be -32768/32767
upper_bound cause an integer overflow so the statement if (getPosition() >= lower_bound && getPosition() <= upper_bound) { is never true because upper_bound is considered -32768 like lower_bound.
consequently, having lower_bound and upper_bound at the same value make any movement ignored because you can never have another value.
just initialize your ESPRotary object with custom values for lower_bound and upper_bound like this:
ESPRotary r = ESPRotary(ROTARY_PIN1, ROTARY_PIN2, CLICKS_PER_STEP, -32768, 32767);
and you should be good.