Go Down

Topic: Encoder and Interrupts (Read 629 times) previous topic - next topic

WilliamK Govinda

Dec 03, 2010, 12:45 am Last Edit: Dec 03, 2010, 12:46 am by WilliamK Reason: 1
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...  :-[
Code: [Select]
#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....  :(



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 - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131