Hello everyone,
I'm new to this forum and I'm here cause I ran into a problem with my robot.
I started writing some code for it but for some reason it works really well when plugged into my computer, but when I detach the cable and leave the robot alone on its batteries the robot is not doing what it should do anymore. Here's the (rather simple) code I've written for it already.
#define ENABLE_A 0
#define ENABLE_B 1
#define IN1 2
#define IN2 3
#define IN3 4
#define IN4 5
#define trigpin 6
#define echopin 7
#define trigpin2 8
#define echopin2 9
#define MAX_DISTANCE 154
void setup() {
Serial.begin(115200);
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(trigpin2, OUTPUT);
pinMode(echopin2, INPUT);
pinMode(ENABLE_A, OUTPUT);
pinMode(ENABLE_B, OUTPUT);
pinMode(IN1,OUTPUT);
pinMode(IN2,OUTPUT);
pinMode(IN3,OUTPUT);
pinMode(IN4,OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);
duration = pulseIn(echopin, HIGH);
distance = (duration/2)/29.1;
if (distance >= 154 || distance <= 0)
{
Serial.println ("nope");
}
else
{
Serial.print(distance);
Serial.println("cm");
}
long duration2, distance2;
digitalWrite(trigpin2, LOW);
delay(2);
digitalWrite(trigpin2, HIGH);
delay(10);
digitalWrite(trigpin2,LOW);
duration2 = pulseIn(echopin2, HIGH);
distance2 = (duration2/2)/29.1;
if (distance2 >= 154 || distance2 <= 0)
{
Serial.println ("nope2");
}
else
{
Serial.print(distance2);
Serial.println("cm");
}
if (distance < 5)
{
digitalWrite(ENABLE_A, HIGH);
digitalWrite(ENABLE_B, HIGH);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
}
else if (distance2 < 5)
{
digitalWrite(ENABLE_A, HIGH);
digitalWrite(ENABLE_B, HIGH);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
else
{
digitalWrite(ENABLE_A, HIGH);
digitalWrite(ENABLE_B, HIGH);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
}
Is there something wrong with the code, or is there a hardware problem?
Thanks for your help in advance!
Charles