I have made a robot with 2 gear motors, a led and a servo
I have written in my code that when I press 1,2,3,7,5,9 some functions go on like the robot moving forward etc
The 2 motors are used to move the robot and the servo and led are used as a gun turret.
When I give commands to my motors my servo goes jerky for a while and stops but some times it goes jerky and never stops unless I plug out the arduino.
Please help me to solve this problem
The code is :
#include <Servo.h>
int LedPin1 = 12;
int LedPin = 13;
int MotorPin1 = 9;
int MotorPin2 = 10;
int servoPin = 11;
Servo VishalServo;
void setup()
{
digitalWrite(LedPin, HIGH);
Serial.begin(9600);
pinMode(LedPin, OUTPUT);
pinMode(LedPin1, OUTPUT);
pinMode(MotorPin1, OUTPUT);
pinMode(MotorPin2, OUTPUT);
VishalServo.attach(servoPin);
VishalServo.writeMicroseconds(1500);
delay(2000);
}
void loop()
{
while (Serial.available() == 0);
int val = Serial.read() - '0';
int i = VishalServo.read();
if (val == 2)
{
Serial.println("Robot is On");
digitalWrite(MotorPin1, HIGH);
digitalWrite(MotorPin2, HIGH);
delay (1000);
digitalWrite(MotorPin1, LOW);
digitalWrite(MotorPin2, LOW);
}
if (val == 1)
{
Serial.println("Robot is turning left");
digitalWrite(MotorPin2, HIGH);
delay(1000);
digitalWrite(MotorPin2, LOW);
}
if (val == 3)
{
Serial.println("Robot is turning right");
digitalWrite(MotorPin1, HIGH);
delay(1000);
digitalWrite(MotorPin1, LOW);
}
if (val == 7)
{
Serial.println("Turning left");
VishalServo.write(i+30);
}
if (val == 9)
{
Serial.println("Turning right");
VishalServo.write(i-30);
}
if (val == 5)
{
Serial.println("Shoot");
digitalWrite(LedPin1, HIGH);
delay(25);
digitalWrite(LedPin1, LOW);
}
if (val == 8)
{
Serial.println("Centering");
VishalServo.writeMicroseconds(1500);
}
else
{
Serial.println("Invalid!");
}
}