Programming a Servo Motor to respond to User Input in the Serial Input Monitor

I need some help with this code (see below).

I'm trying to get the code to respond by switching off the LED and moving from 180 deg to 0 deg when I input CLOSED in the serial input monitor. Testing shows the input = "OPEN" is constantly overriding any other inputs and I can't figure out why. Any suggestions on where I'm going wrong?

I'm using an ESP32 board and a servo motor, modelled on wokwi.com
https://wokwi.com/projects/326029589330526803

#include <WiFi.h>
#include <ESP32Servo.h>

Servo myservo; //create servo object to control servo

int pos = 0; //variable to store server position
static const int servoPin = 18;

const int LED = 12;

String command;

void setup(){
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  //allow allocation of all timers
  ESP32PWM::allocateTimer(0);
	ESP32PWM::allocateTimer(1);
	ESP32PWM::allocateTimer(2);
	ESP32PWM::allocateTimer(3);
	myservo.setPeriodHertz(50); //standard 50hz servo
  myservo.attach(servoPin, 10, 2800); // attaches the servo on pin 18 to the servo object
  pinMode(LED, OUTPUT);
  Serial.println("Door is ");
}

void loop(){

while (Serial.available() >0 ){
 String command = Serial.readString();

 if (command == "OPEN"){
   Serial.println(command);
    for (pos = 0; pos<=180; pos+=1){
      myservo.write(pos);
      digitalWrite(LED,HIGH);
      delay(15);
      }
    }

  if (command == "CLOSED"){
    Serial.println(command);
    for (pos = 180; pos<=0; pos-=1){
      myservo.write(pos);
      digitalWrite(LED,LOW);
      delay(15);
      }
    }
  }
}
//Serial.print(pos);

start simple. consider

#include <Servo.h>
Servo myservo; //create servo object to control servo

static const int servoPin = 18;
const int LED = LED_BUILTIN;        // Arduinoe
String command;

void setup(){
    Serial.begin(115200);

    myservo.attach(servoPin, 10, 2800); // attaches the servo on pin 18 to the servo object
    pinMode(LED, OUTPUT);
    Serial.println("Door is ");
}

void loop(){
    while (Serial.available() >0 ){
        String command = Serial.readString();
        Serial.println(command);

        if (command == "OPEN"){
            digitalWrite(LED,HIGH);
            for (int pos = 0; pos<=180; pos+=1)
                myservo.write(pos);
        }

        if (command == "CLOSED"){
            digitalWrite(LED,LOW);
            for (int pos = 180; pos<=0; pos-=1)
                myservo.write(pos);
        }
    }
}

check serial monitor line terminator -- needs to be none

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.