Reading Encoders with Arduino

We will be updating this page for our new encoders that have only one output.

Introduction:

When an encoder is spinning full speed, it can be outputting more than 3000ticks/second. In order to count all of these ticks, we will need a very fast code that runs in the "background" of our main code. Unfortunately, Arduino does not offer real time processing or parallel threads, so the next closest thing are interrupts.

Interrupts:

Arduino UNO has two external interrupt pins: Digital pin 2 and 3. By using the attachInterrupt function, you use an external signal attached to pin 2 and 3 to interrupt your code. For more details, see: attachInterrupt

Encoder Test Code:

Wiring Instructions (pololu motor):

copy and paste code into a new sketch:

#include <avr/io.h>

#include <avr/interrupt.h>

#include <math.h>

//Define Pins

#define EncoderPinA 2 // Encoder Pin A pin 2 and pin 3 are inturrpt pins

#define EncoderPinB 5 // Encoder Pin B

//Initialize Variables

long counts = 0; //counts the encoder counts. The encoder has ~233counts/rev

void setup() {

Serial.begin(115200);

pinMode(EncoderPinA, INPUT); //initialize Encoder Pins

pinMode(EncoderPinB, INPUT);

digitalWrite(EncoderPinA, LOW); //initialize Pin States

digitalWrite(EncoderPinB, LOW);

attachInterrupt(0, readEncoder, CHANGE); //attach interrupt to PIN 2

}

void loop() {

Serial.println(counts);

}

void readEncoder() //this function is triggered by the encoder CHANGE, and increments the encoder counter

{

if(digitalRead(EncoderPinB) == digitalRead(EncoderPinA) )

{

counts = counts-1; //you may need to redefine positive and negative directions

}

else

{

counts = counts+1;

}

}