arduinoservoserial-monitor

How to move 2 separate servos in Serial monitor


#include <Servo.h>
Servo servo1;
Servo servo2;


void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
servo1.attach(6);
servo1.write(0);
servo2.attach(7);
servo2.write(0);
}

void loop() {
  // put your main code here, to run repeatedly:
String readString;
String Q;
String V1Val;
int v1;

//-------------------------------Check Serial Port---------------------------------------
 while (Serial.available()) {
    delay(1);  //delay to allow buffer to fill 
    if (Serial.available() >0) {
      char c = Serial.read();  //gets one byte from serial buffer
    if (isControl(c)) {
      //'Serial.println("it's a control character");
      break;
    }
      readString += c; //makes the string readString    
    }
 }   

 Q = readString;
//--------Checking Serial Read----------
      

        if(Q.substring(0,1)=="S"){
        V1Val = Q.substring(1);
        v1 = V1Val.toInt();

        delay(100);     
        servo1.write(v1);   
        servo2.write(v1);             
      }

    
}

I want this code to work with 2 servos but separately in the Serial monitor Example: S100 To move 1 servo to 100 degrees and Q50 To move servo number 2 to 50 degrees I got this code from someone else so i dont know how to make it work for 2 servos separately


Solution

  • You can copy the same idea from servo1 to servo2:

      if (Q.substring(0, 1) == "S") {
        V1Val = Q.substring(1);
        v1 = V1Val.toInt();
    
        delay(100);
        servo1.write(v1);
      }
    
      if (Q.substring(0, 1) == "Q") {
        V1Val = Q.substring(1);
        v1 = V1Val.toInt();
    
        delay(100);
        servo2.write(v1);
      }