Pages: [1]   Go Down
Author Topic: Encoder and Interrupts  (Read 450 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
God Member
Karma: 3
Posts: 626
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Guys, I got a nice encode code working on my Arduino MEGA. BUT, I wish to use Interrupts, so I can check when the encoder is moved very fast and jump to MAX or MIN. Also bypass any problems of not checking the encoder code often...

So, here's the code I'm using. But I got no clue on how to make it work with an Interrupt...  :-[
#define dpInEncoderA 20
#define dpInEncoderB 19
int EncoderPos = 120;
int Position, Press;
int isForward = 0;
int Position2, Press2;

void ReadEncoder(int &rotate) { rotate = (digitalRead(dpInEncoderB) * 2) + digitalRead(dpInEncoderA); }
void ReadEncoderI()
  if (Position2 != Position)
    int isFwd = ((Position == 0) && (Position2 == 1)) ||
                ((Position == 1) && (Position2 == 3)) ||
                ((Position == 3) && (Position2 == 2)) ||
                ((Position == 2) && (Position2 == 0));
    if (isFwd) EncoderPos++; else EncoderPos--;
    if (EncoderPos <= 0) EncoderPos = 1;
    if (EncoderPos > 255) EncoderPos = 255;
  Position = Position2;

void setup()
  // Encoder //
  pinMode(dpInEncoderA, INPUT);
  digitalWrite(dpInEncoderA, HIGH);
  pinMode(dpInEncoderB, INPUT);
  digitalWrite(dpInEncoderB, HIGH);

void loop()

I'm pretty sure the code is all wrong, as its very late here and I'm very tired...  :o  :'(

Tomorrow I will run more tests and see if I can figure this one out. If I can't, I will give up for the moment....  smiley-sad

« Last Edit: December 02, 2010, 06:46:25 pm by WilliamK » Logged

Global Moderator
Offline Offline
Shannon Member
Karma: 227
Posts: 14024
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Part of the trick using interrupts is doing as less as possible in the interrupt routine. Be sure not to use a Serial.print() as these take far too long.
Second, declare the variables used in the IRQ as volatile, to prevent the compiler to optimize access.

Rob Tillaart

Nederlandse sectie -,77.0.html -
(Please do not PM for private consultancy)

Pages: [1]   Go Up
Jump to: