Hi, 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.
Check the connections of the A and B pins from the encoder. If the processor gets only the A or only the B it can still count, but has not way to know direction.
Attached is data sheet. It works fine for me, but maybe I am doing something wrong I don't even know about. How would I check the A+B pins, I have tried changing the jumper wires and using different pins on the board with no luck.
Use your multimeter to read out the logic levels on each of the encoder outputs, as you very slowly rotate the motor shaft by hand. Are they what you expect?
It is pretty hard to debug a problem like this if you don't know what to expect. Study this tutorial to learn how quadrature encoders work.
In summary, a quadrature encoder has two pins, and two voltages. The voltages should go "up and down" as the shaft rotates, according to this diagram:
If they don't, there is a wiring problem, or a defective encoder.
Finally, have you checked whether ENC1A and ENC2A pins actually support rising edge interrupts?
Edit: I just noticed that you violated two important rules. Variables shared with interrupt routines MUST be declared volatile, and protected from corruption by the interrupt, when accessed by the main routine.
volatile int apos = 0;
volatile int bpos = 0;
...
noInterrupts();
int apos_copy=apos;
int bpos_copy=bpos;
interrupts();
Serial.print("A Pos = ");
Serial.print(apos_copy); //avoid using Strings!
Serial.print(" B pos = ");
Serial.println(bpos_copy);