Help!!! Rotary Encoders keep changing their Mind.

I’m having loads of fun trying to figure this out, but unfortunately I’m working till a deadline to get a working motor. I’m having issues with my robot, it seems to enjoy working on and off, in that when I program(?) the encoders to count over a specific distance it often decides it will travel varying distances instead. eg.

float j=0; //not seen below, using this float with a count based on the arduino chips clock to set a servo to run for x(seconds).
int initial=LOW;
int i=0;
int E1=5; //Left Motor, HIGH = motor on, LOW = motor off
int E2=6; //Right Motor
int M1 = 4; //M1 Direction Control, CHANGE causes the motor to reverse direction.
int M2 = 7; //M2 Direction Control
int encoder = 3; //digital input that encoder is plugged into

void setup(){
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);

void forward(int a){
while (i<a){
if (digitalRead(3)!=initial){
initial = digitalRead(3);

void loop(){
if (i==0);
forward(x); // x is set at any value between 0 and 3000

The kit I’m using for this project is a pairing of the ‘ROVER 5’ robot platform(, and the DFR-Romeo 1.0 (

I’m powering the encoders from an external 9V battery, however, beforehand I was also running the encoder from the internal power (5V) and still having the same issues. I’ve written the code above not using the attachInterrupt() as before when I was, the same issue was still occuring.

Any ideas as to why I might be having these problems?
Thanks :slight_smile:

I know you saw it too.

void loop(){ if(i==0){ forward(x); digitalWrite(E1,LOW); digitalWrite(E2,LOW); }

so that the motors stop, whoops :s

  while (i<a){
    if (digitalRead(3)!=initial){
      initial = digitalRead(3);

You assigned the value 3 to encoder, supposedly to make it clear that you are reading the encoder. So, why the hardcoded 3 here?