I'm sure time has already passed for this persons project. But for those visiting this page for whatever reason (mine was different than the information here) here is a solution I would implement. Also this is assuming the individual is not willing to use a latched external buffer where they can read from it however they need to. Simply split the total pins among 2 registers making sure the following
- The pins used are in sequential order to both the MCU and the encoder (gray coding will require some thought to this).
- Group as many on a single register as possible and this will be the low order value.
Read from the low order value first (the one that will be changing at the highest rate). Then read from the high order value (where it will be far less likely to change between the low order and the high order read). You need to understand bit masks and bit shifting to do this...
uint16_t nEncoder = (PINB & 0x1F); // Example if your 5 pins are the low ones on PORTB
uint16_t nEncoder = ((PINB & 0x7C) >> 2); // Example if your 5 pins are 6:2 where you pull your set of pins off of PORTB then bitshift them down into their proper place.
then you read in the high order part
nEncoder |= ((PIND & 0x1F) << 5); // Example if your 5 pins are the low ones on PORTD. However you pull them off of the next port, you will need to make sure you bitshift them into the upper 10 bits of nEncoder to get your final value.
In the above, you can see that the more bits (pins) you can use on your first register (port), the less likely your second read will have a pin change.
Gray coding will be different than binary. The above example assumes binary where the high order bit will change the least and the low order the most. Gray coding is specifically used because of how minimally the bits change in-between each number change (i.e. they are suppose to only have 1 bit change per number change no matter the number rather than 10 bits change when a binary count rolls over - i.e. it minimizes this exact problem). So for the original poster, most of this should be irrelevant (since they said they were using a gray code encoder).
But for those seeking an optimal solution (for binary counters or just because) where they cannot stick all pins on a single port. Splitting it between two registers with only two reads will optimize your read time and minimize the pin change possibility.