Hi,
I am working on a project which uses a couple of mcp23017s on the i2c bus and trying to read rotary encoders.
I have a quite common problem.
I can determine the direction of rotation when I am rotating slowly but as soon as i turn it quick, the reading is a mess. Sometimes shows opposite direction, sometimes nothing. As i kept searching on google, i found out how exactly encoders work and why the problem occurs. Although I foind only one answer about arduino and mcp23017: "dont turn it quick". In my case it is not an option.
I found a code on a site, which is very promising, and there is a good description(even thouhgh i dont fully understamd it). But this is if the encoder is connected directly to the arduino. The question is how can I turn this to work with the mcp 23017?
/* Rotary encoder read example */
#define ENC_A 14
#define ENC_B 15
#define ENC_PORT PINC
void setup()
{
/* Setup encoder pins as inputs */
pinMode(ENC_A, INPUT);
digitalWrite(ENC_A, HIGH);
pinMode(ENC_B, INPUT);
digitalWrite(ENC_B, HIGH);
Serial.begin (115200);
Serial.println("Start");
}
void loop()
{
static uint8_t counter = 0; //this variable will be changed by encoder input
int8_t tmpdata;
/**/
tmpdata = read_encoder();
if( tmpdata ) {
Serial.print("Counter value: ");
Serial.println(counter, DEC);
counter += tmpdata;
}
}
/* returns change in encoder state (-1,0,1) */
int8_t read_encoder()
{
static int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
static uint8_t old_AB = 0;
/**/
old_AB <<= 2; //remember previous state
old_AB |= ( ENC_PORT & 0x03 ); //add current state
return ( enc_states[( old_AB & 0x0f )]);
}
For example I dont understand what is PINC and the line before the last one.
I am also thinking it would be more efficient to use the SPI version of the IC. I heard it may be faster. And since i am working on a big project with a switch matrix some MAX 7221s that must control hundreds of leds and some servos with a servo controller ic and multi position switches will also add up to the project. And the whole thing would communicate with a pc on the serial bus. So im not even sure if one single arduino mega will be enough for the whole project without getting slow.
So my question is how to get my encoders working properly at higher speed rotations and should I use the SPI or the I2C version of the IC?
Thanks in advance.