I have a new NodeMCU ESP8266. I made sure that the builtin LED on it was working properly by uploading the "Blink" example sketch from the Arduino IDE examples and it worked. When I try my own code to make the LED turn on or off using commands from the serial monitor or audio input the LED simply stays lit the whole time.
I have also made sure that the serial monitor is working by logging (Serial.println(command)
) the command that I send to the COM3 port to which my NodeMCU is connected.
How should I go about solving this?
My code (I have copied this from the internet after my debugging efforts on my own code failed but this also did not work):
int led = LED_BUILTIN;
void setup()
{
Serial.begin(9600); //Baud Rate
pinMode(led, OUTPUT);
}
void loop()
{
char data = Serial.read();
switch (data) //Selection Control Statement
{
case 'ON':
digitalWrite(led, HIGH); // Sets the led ON
break;
case 'OFF':
digitalWrite(led, LOW); //Sets the led OFF
break;
}
}
EDIT: My original code:
String cmnd = "";
void setup()
{
Serial.begin(9600);
Serial.setTimeout(10);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop()
{
while(Serial.available() == 0) {}
cmnd = Serial.readString();
if(cmnd == "on") {
Serial.println(cmnd);
digitalWrite(LED_BUILTIN, HIGH);
} else if (cmnd == "off") {
Serial.println(cmnd);
digitalWrite(LED_BUILTIN, LOW);
}
}
```
data = Serial.read()
just return one character? You'll get anO
the first time andF
for the next two reads. Try changing tocase 'N'
andcase 'F'
instead. \$\endgroup\$