Encoders Working

My encoders are now working! I am using US Digital encoders (the expensive kind) and they work great! I had a little
trouble getting the right encoder to work, but that is all over now. The problem was that I had forgotten to put a 0.1µF capacitor across the two motor leads, resulting in major electronic noise. The other problem was that there was no data coming in from the right encoder. It turned out to be a bad jumper.

If it is useful to anybody, here is the arduino code I wrote to print the data from both encoders:

volatile long RightDistance = 0;
volatile long LeftDistance = 0;

long PreviousLeftDistance = 0;
long PreviousRightDistance = 0;

#define RightEncoderPinA 18  // connect right encoder wire A to pin 2
#define LeftEncoderPinA 19   // connect left encoder wire A to pin 3
#define RightEncoderPinB 50  // connect right encoder wire B to pin 13
#define LeftEncoderPinB 51   //connect left encoder wire B to pin 14

#define RightEncoderInterupt 5  //the interupt number for the right encoder
#define LeftEncoderInterupt 4   //the interupt number for the left encoder

void setup()
{
  Serial.begin(9600);  // open the serial port at 9600 bps:

  attachInterrupt(RightEncoderInterupt, RightEncoderISR, CHANGE); // connect encoder wire A to pin 5 (RightEncoderInterupt)
  attachInterrupt(LeftEncoderInterupt, LeftEncoderISR, CHANGE);   // connect encoder wire A to pin 4 (LeftEnocderInterupt)

  pinMode(RightEncoderPinA, INPUT);  // set the RightEncoderPinA to input
  pinMode(RightEncoderPinB, INPUT);  // set the RightEncoderPinB to input
  pinMode(LeftEncoderPinA, INPUT);   // set the LeftEncoderPinA to input
  pinMode(LeftEncoderPinB, INPUT);   // set the LeftEncoderPinB to input
}

void loop()
{
  if ((RightDistance != PreviousRightDistance) | (LeftDistance != PreviousLeftDistance))  //this makes the distance print only when it changes
  {
    Serial.print(" Right ");
    Serial.print(RightDistance);  //print the RightDistance
    Serial.print(" Left ");
    Serial.print(LeftDistance);   //print the RightDistance
    Serial.println("");
  }

  PreviousLeftDistance = LeftDistance;
  PreviousRightDistance = RightDistance;
}

//the logic for the right encoder
void RightEncoderISR()
{
  if (RightEncoderPinA == RightEncoderPinB)
  {
    RightDistance--;
  }
  else
  {
    RightDistance++;
  }
}

//the logic for the left encoder
void LeftEncoderISR()
{
  if (LeftEncoderPinA == LeftEncoderPinB)
  {
    LeftDistance--;
  }
  else
  {
    LeftDistance++;
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: