So my robot does work when it is connected to us or usb and 9V, but when it is connected only to the 9V
Everything works with little pulses and long delays!
Is this a good code even?
#include <Servo.h>
Servo servo; //Create a servo object
//Standard PWM DC control
int E1 = 5; //M1 Speed Control
int E2 = 6; //M2 Speed Control
int M1 = 4; //M1 Direction Control
int M2 = 7; //M2 Direction Control
int a = 100; //Standard speed values
int b = 100;
int Left = 0;
int Right = 0;
int Seek = 0;
int IRPin = A1; //IR Sensor
void brake() //Stop
{
digitalWrite(E1,LOW);
digitalWrite(E2,LOW);
}
void forward() //Move forward
{
analogWrite (E1,a); //PWM Speed Control
digitalWrite(M1,HIGH);
analogWrite (E2,b);
digitalWrite(M2,HIGH);
}
void turn_L() //Turn Left
{
analogWrite (E1,a);
digitalWrite(M1,LOW);
analogWrite (E2,b);
digitalWrite(M2,HIGH);
}
void turn_R() //Turn Right
{
analogWrite (E1,a);
digitalWrite(M1,HIGH);
analogWrite (E2,b);
digitalWrite(M2,LOW);
}
void detect()
{
brake();
servo.write(0);
delay(1000);
Left = analogRead(IRPin);
servo.write(160);
delay(1000);
Right = analogRead(IRPin);
compare();
}
void compare()
{
if (Left > Right)
{
turn_R();
delay(1000);
}
else
{
turn_L();
delay(1000);
}
brake();
}
void setup()
{
servo.attach(9); //Servo to pin 9
int i;
for(i=4;i<=7;i++) //This one shortens the code, a LOT! It sets up output pins
pinMode(i, OUTPUT);
}
void loop()
{
servo.write(90);
Seek = analogRead(IRPin);
if (Seek > 399)
{
detect();
}
else
{
forward();
}
}