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);