Multi Encoders using a Timer...

So, 1,000 people would have 1,000 different approaches to the same problem... therefore, here's my own solution. :wink:

Currently I'm using Timer2 to do PWM on multiple leds via SPI and C595 shift-chips. It works great. But, I was out of pins to add multiple-encoders on our Beat707.com board. Well, I knew there must be a way to add encoders, but they "require" interrupt pins, right? Well, depends... since the timer is always checking the SPI chips, including multi-C165 chips for 32 inputs, we had 8 non-used external button connections that are read via SPI using C165 chips.

All I had to do is connect the encoder on 2 of those button-jumpers, and do a simple code.

First, how the heck a 2-bit encoder works? Well, its actually simple, like this:

00 01 11 10 00
or
00 10 11 01 00

Depending on the direction.

Heck, that's simple, I can do a small code to check that. Them I will store the number of clicks/turns into a variable that is check on the loop, and does what it needs to do. :wink: And since I can miss ticks, I don't need interrupts. (this is just an interface encoder anyway)

So, here's the code:

    if (bitRead(extraExternal,2) == 0 && bitRead(extraExternal,3) == 0) prevEncBt = 0;
    else if (bitRead(extraExternal,2) == 1 && bitRead(extraExternal,3) == 0) prevEncBt = +1;
    else if (bitRead(extraExternal,2) == 0 && bitRead(extraExternal,3) == 1) prevEncBt = -1;
    else if (bitRead(extraExternal,2) == 1 && bitRead(extraExternal,3) == 1 && prevEncBt != 0)
    {
      if (prevEncBt > 0)
      {
        if ((millisNI()-encoderMillis) < 25) globalEncoder[0] += 4; else globalEncoder[0]++;
        encoderMillis = millisNI();
      }
      else
      {
        if ((millisNI()-encoderMillis) < 25) globalEncoder[1] += 4; else globalEncoder[1]++;
        encoderMillis = millisNI();        
      }
      prevEncBt = 0;
    }

I'm checking the timing of each click so I know if its moving faster or slower, therefore, I don't need to worry about losing ticks.

Wk

Well, I knew there must be a way to add encoders, but they "require" interrupt pins, right?

Where did you get that wisdom from? Rotary encoders specially for user input don't need interrupts, they can be safely be polled. Just look up the various standard solutions how to handle that, most of them in a more elegant way than your code. Reading the bit in every if-statement usually isn't the best idea and the decoding is far easier to understand and compact by doing it via a table. That only takes 4 bytes of data and 2 compares.

Korman