When I connect the FTDI cable to Arduino, the whole robot starts working and executes a basic object-avoidance code. When I take it off and connect the power source, the robot starts to execute bits of code in a random sequence. The Arduino isn't resetting, but the red light is varying in intensity. Sometimes it almost goes out. I'm using an Arduino Pro Mini. Because the green light doesn't blink, I suppose the 2AA batteries aren't good enough to dish out 2A or more (I use 2 GM9 motors and I geard Arduino can use up to 1A). The motors are running faster and firmer whith the cable, but they struggle without. Here's the code:
const int pingPin = 9;
int Ain1 = 11;
int Ain2 = 12;
int Bin1 = 7;
int Bin2 = 8;
int Pwma = 6;
int Pwmb = 5;
int Stby = 10;
void setup() {
pinMode(Ain1, OUTPUT);
pinMode(Ain2, OUTPUT);
pinMode(Bin1, OUTPUT);
pinMode(Bin2, OUTPUT);
pinMode(Pwma, OUTPUT);
pinMode(Pwmb, OUTPUT);
pinMode(Stby, OUTPUT);
digitalWrite(Stby, HIGH);
analogWrite(Pwma, 255);
analogWrite(Pwmb, 255);
Serial.begin(9600);
}
void loop()
{
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
delay(500);
if(cm < 15)
{
digitalWrite(Ain1, HIGH);
digitalWrite(Ain2, LOW);
digitalWrite(Bin1, HIGH);
digitalWrite(Bin2, LOW);
delay(1000);
digitalWrite(Ain1, HIGH);
digitalWrite(Ain2, LOW);
digitalWrite(Bin1, LOW);
digitalWrite(Bin2, HIGH);
delay(500);
digitalWrite(Ain1, LOW);
digitalWrite(Ain2, LOW);
digitalWrite(Bin1, LOW);
digitalWrite(Bin2, LOW);
}
else
{
digitalWrite(Ain1, LOW);
digitalWrite(Ain2, HIGH);
digitalWrite(Bin1, LOW);
digitalWrite(Bin2, HIGH);
delay(100);
}
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}