Skip to content

Instantly share code, notes, and snippets.

@jrsphoto
Created September 20, 2019 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrsphoto/0d63d19251941ac87dd2747a20a435dc to your computer and use it in GitHub Desktop.
Save jrsphoto/0d63d19251941ac87dd2747a20a435dc to your computer and use it in GitHub Desktop.
// see http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1267553811/0
// and http://code.google.com/p/digitalwritefast/
// It turns out that the regular digitalRead() calls are too slow and bring the arduino down when
// I use them in the interrupt routines while the motor runs at full speed creating more than
// 40000 encoder ticks per second per motor.
// Tuning encoder
#define c_EncoderAInterrupt 18
#define c_EncoderPinA 18
#define c_EncoderPinB 19
#define EncoderIsReversed
volatile bool _EncoderBSet;
volatile long _EncoderTicks = 0;
void setup()
{
Serial.begin(115200);
// Quadrature encoders
// Left encoder
pinMode(c_EncoderPinA, INPUT); // sets pin A as input
digitalWrite(c_EncoderPinA, LOW); // turn on pullup resistors
pinMode(c_EncoderPinB, INPUT); // sets pin B as input
digitalWrite(c_EncoderPinB, LOW); // turn on pullup resistors
attachInterrupt(c_EncoderAInterrupt, HandleEncoderInterruptA, RISING);
}
void loop()
{
Serial.print(_EncoderTicks);
Serial.print("\n");
delay(20);
}
// Interrupt service routines for the quadrature encoder
void HandleEncoderInterruptA()
{
// Test transition; since the interrupt will only fire on 'rising' we don't need to read pin A
_EncoderBSet = digitalReadFast(c_EncoderPinB); // read the input pin
// and adjust counter + if A leads B
#ifdef EncoderIsReversed
_EncoderTicks -= _EncoderBSet ? -1 : +1;
#else
_EncoderTicks += _EncoderBSet ? -1 : +1;
#endif
}
@jrsphoto
Copy link
Author

I have not tried this code with an Arduino, only the Teensy 3.6, though I suspect it would work well on the Teensy 3.2 or 4.0 as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment