Arduino servo motors and serial monitor suddenly "crash"

1.5k views Asked by At

I have been trying to control my 2 servo motors trought serial monitor. When i enter number 1-5 to serial monitor it follows the command as told in code. I write in the numbers 1-5 a couple of times and servos suddenly stop and i cant enter anything in serial monitor anymore. It worked fine when i only had the moving forward part of the code.

enter image description here

#include <Servo.h> 

Servo servo1;
Servo servo2;            

int servodata;

void setup() 
{ 
Serial.begin(9600);  
Serial.println("Redy");
Serial.println("1 stop ");
Serial.println("2 forward");
Serial.println("3 backward");
Serial.println("4 Turn left");
Serial.println("5 Turn right");

   servo1.attach(D7) ;
   pinMode(D7, OUTPUT);
    servo2.attach(D8) ;
    pinMode(D8, OUTPUT);




} 

void loop() 
{

  if (Serial.available() > 0)
  {
     servodata = Serial.read();

 if(servodata == '1') // Single Quote! This is a character.
  {
  Serial.println("Stop");
  {                                 
servo1.write(90); //stop 
servo2.write(90);   
 delay(3000);                 
  } 
    }


    if(servodata == '4')
    {
      Serial.println("Turn left");
      {
  servo1.write(0);  //Turn left
  servo2.write(0); 
  delay(3000);
} 
    }

    if(servodata == '5')
    {
      Serial.println("Turn right");
      {
  servo1.write(180);  //Turn right
  servo2.write(180); 
  delay(3000);
    } 
        }


    if(servodata == '2')
    {
      Serial.println("Forward");
      {
  servo1.write(0);  //Forward
  servo2.write(180); 
  delay(3000);
} 
    }

   if(servodata == '3')
    {
      Serial.println("Backward");
  {
servo1.write(180); //Backward
  servo2.write(0);
   delay(3000);
    }
    }


    Serial.println(" ");    // End the line


  }
    }
1

There are 1 answers

8
Cihan Kurt On

I think it happens because of the Serial communication. Serial at 9600 BAUD is VERY SLOW and stalls the server. Try removing the Serial prints, if it's still freezing then the problem is something else.