Errors in program execution when using external power supply

Hi,
I'm using my Arduino Uno to read a stepper motor and a few sensors. I count the steps using interrupts, and so far it works fine up to ~120kHz (I've tested it using another Arduino).

However problems occur when I use external power supply and do not have it plugged into my pc: The Arduino seems to work fine, but it miscounts even even at speeds of 0.1 - 1 kHz, although I do not even use any serial communication.

I would appreciate if someone could help me, after all it should work the same way with an external power source?
I've attached a simplified version of the source code.

Yours, prooq

#define encoderPinA 2               // Encoder pins
#define encoderPinB 3

#include <LiquidCrystal.h>

volatile long int encoder;          // Encoder position
volatile byte Aold;                 // Last encoder states
volatile byte Bold;                 // (volatile declarations for interrupt variables)
long int old_encoder;               // Last position
LiquidCrystal lcd(5, 6, 7, 8, 9, 10, 11);


void setup() {
  randomSeed(analogRead(0));
  digitalWrite(encoderPinA, HIGH);               // Turn on pullup resistors on encder pins
  pinMode(encoderPinA, INPUT);                   // and set pins to input.
  digitalWrite(encoderPinB, HIGH);
  pinMode(encoderPinB, INPUT);            
  Aold = digitalRead(encoderPinA);               // Read initial state of encoder
  Bold = digitalRead(encoderPinB);
  attachInterrupt(0, doEncoderA, CHANGE);        // Encoder A on interrupt 0 (pin 2)
  attachInterrupt(1, doEncoderB, CHANGE);        // Encoder B on interrupt 1 (pin 3)

  old_encoder = encoder;                         // Enter peacefully (no position change yet)
  lcd.begin(16,2);
  lcd.print("Encoder position");

}

void loop(){

  if (old_encoder != encoder) {                    // Check for changes in encoder position
    old_encoder = encoder;                   // Encoder changed; reset old encoder position
    lcd.setCursor(0,1);    
    lcd.print(encoder);      
  }

}

void doEncoderA(){                           // Interrupt on A (pin 2)
  Aold == Bold ? encoder++ : encoder--;      // increase : decrease encoder value
  Aold = !Aold;                              // update state of pin A
}

void doEncoderB(){                           // Interrupt on B (pin 3)
  Aold != Bold ? encoder++ : encoder--;      // increase : decrease encoder value
  Bold = !Bold;                              // update state of pin B
}

Your problem has nothing to do with the code. If it works on USB power it will work with external power. When it doesn't work you have wired it up incorrectly, maybe a ground has not been wired up.

Oh, well, indeed it did not have a proper ground when USB was disconnected :S

Thank you, that was a simpler solution then I had been looking for :slight_smile: