Encoder values only moving in one direction on one motor, work properly on the other

Viewed 25

I have two motors plugged into an arduino mega as shown in the diagram below however when I rotate motor b it works totally fine and the encoder shows the increase or decrease in values, however, for it just decreases without stop. does anybody know why this might happen and how to fix it? Code and pinout below. enter image description here

#include <Arduino.h>

#define ENC1A 3
#define ENC1B 2

#define ENC2A 20
#define ENC2B 21


int apos = 0;
int bpos = 0;

void readEncoderA()
{
    int a = digitalRead(ENC2A);
    if(a>0){
        apos++;
    }
    else {
        apos--;
    }
}

void readEncoderB()
{
    int b = digitalRead(ENC2B);
    if(b>0){
        bpos++;
    }
    else {
        bpos--;
    }
}

void setup() 
{
    Serial.begin(9600);
    pinMode(ENC2A, INPUT);
    pinMode(ENC2B, INPUT);
    pinMode(ENC1A, INPUT);
    pinMode(ENC1B, INPUT);
    attachInterrupt(digitalPinToInterrupt(ENC1A), readEncoderA, RISING);
    attachInterrupt(digitalPinToInterrupt(ENC2A), readEncoderB, RISING);
}

void loop()
{
    Serial.println("A Pos = " + String(apos) + " B pos = " + String(bpos));
}
0 Answers
Related