Hello, I am testing a DC gearmotor with an incremental optical encoder and want to calibrate it for the encoder clicks.
I am using an Arduino Mega 2560 and using pins 2 and 3 for A and B outputs of the encoder. I am using a Cytron MD 13S motor driver. The PWM output is connected to Mega's pin 4 and Direction outputput is connected to pin 7.
When I run the code without the encoders with interrupts it works fine but with the interrupts, the motor just keeps going and going as though the delay (1000) in line 28 doesn't exist. The debugging line after that doesn't appear on the serial monitor. What am I doing wrong? There are no compiler errors.
#include "CytronMotorDriver.h"
#define encoder0PinA 2
#define encoder0PinB 3
// Configure the motor driver.
CytronMD motor(PWM_DIR, 4, 7); // PWM = Pin 4, DIR = Pin 7.
volatile unsigned int encoder0Pos = 0;
void setup() {
pinMode(encoder0PinA, INPUT);
pinMode(encoder0PinB, INPUT);
// encoder pin on interrupt 0 (pin 2)
attachInterrupt(0, doEncoderA, CHANGE);
// encoder pin on interrupt 1 (pin 3)
//attachInterrupt(1, doEncoderB, CHANGE);
Serial.begin (9600);
}
void loop() {
motor.setSpeed(128); // Run forward at 50% speed.
delay(1000);
Serial.println ("First part Done");
//motor.setSpeed(255); // Run forward at full speed.
//delay(1000);
motor.setSpeed(0); // Stop.
delay(1000);
motor.setSpeed(-128); // Run backward at 50% speed.
delay(1000);
Serial.println ("Second Part Done");
//motor.setSpeed(-255); // Run backward at full speed.
//delay(1000);
motor.setSpeed(0); // Stop.
delay(1000);
}
void doEncoderA() {
// look for a low-to-high on channel A
if (digitalRead(encoder0PinA) == HIGH) {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
else // must be a high-to-low edge on channel A
{
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == HIGH) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
Serial.println (encoder0Pos, DEC);
// use for debugging - remember to comment out
}
void doEncoderB() {
// look for a low-to-high on channel B
if (digitalRead(encoder0PinB) == HIGH) {
// check channel A to see which way encoder is turning
if (digitalRead(encoder0PinA) == HIGH) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
// Look for a high-to-low on channel B
else {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinA) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
}