I'm a newbie to Arduino programming. I have an Arduino Uno with an Arduino Motor Shield and a PING ultrasonic sensor. I'm using the millis() function to fire the PING sensor every 1000 milliseconds. When I test just the PING, its light flashes every second and I get a good reading just as expected. Then when I add the motor controller code in the main loop (using digitalWrite for direction and analogWrite for speed) the light still blinks every second and the motors run the same direction when no objects are detected and opposite directions when an object is 30cm or closer - seems to work great except there's not enough power from the USB to run the motors. Now the really strange part. When I unplug from the USB and use a 9V, the PING light starts blinking rapidly and the motors change unpredictably. When I test just the PING sensor on the 9V, it works fine. Why does the code seem to run differently on USB power versus 9V when motors are in the mix? Are there conflicts in the pins I've chosen? Is my code all wrong? I'm perplexed.
My code:
// pins for motors and PING sensor
const int motorA = 3;
const int motorB = 11;
const int dirA = 12;
const int dirB = 13;
const unsigned int PING = 7;
// program variables
const unsigned int DISTANCE = 30; // in CM
unsigned long start = 1000;
boolean turn = false;
void loop()
{
if (millis() > start) {
turn = detect_object_ahead();
if (turn == true) {
digitalWrite(dirA, LOW);
digitalWrite(dirB, HIGH);
} else {
digitalWrite(dirA, LOW);
digitalWrite(dirB, LOW);
}
analogWrite(motorA, 150);
analogWrite(motorB, 155);
start = millis() + 1000;
}
}
boolean detect_object_ahead() {
pinMode(PING, OUTPUT);
digitalWrite(PING, LOW);
delayMicroseconds(2);
digitalWrite(PING, HIGH);
delayMicroseconds(5);
digitalWrite(PING, LOW);
pinMode(PING, INPUT);
long cm = microseconds_to_cm(pulseIn(PING, HIGH));
if (cm < DISTANCE) {
return true;
} else {
return false;
}
}
unsigned long microseconds_to_cm(const unsigned long microseconds) {
return microseconds / 29 / 2;
}
Thanks for any help,
Brad