Forgive this basic question I tried searching first and could not find a solution. Thank you in advance.
In short I am doing a basic prompt over Serial monitor for a LED toggle. Setting the bool based on input and the led toggle function as intended.
However upon trying to do input validation in the form of an If else statement it appears to be executing the else statement every time. This is in addition to the above if or else if being true. In the case neither are valid the else executes twice.
Serial window output is below. This was after entering t, then Y, then N.
Turn On LED? Y/N
Invalid Input
Invalid Input
LED On
Invalid Input
LED Off
Invalid Input
bool LED;
const int LED_Pin = 12;
void setup() {
// put your setup code here, to run once:
pinMode(LED_Pin, OUTPUT);
Serial.begin(9600);
while (! Serial); // Wait untilSerial is ready - Leonardo
Serial.println("Turn On LED? Y/N");
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available())
{
char ch = Serial.read();
if (ch == 'Y')
{
LED = true;
Serial.println("LED On");
}
else if (ch == 'N')
{
LED = false;
Serial.println("LED Off");
}
else
{
Serial.println("Invalid Input");
}
if (LED == true)
{
digitalWrite (LED_Pin, HIGH);
}
else
{
digitalWrite (LED_Pin, LOW);
}
}
}
Got it, Thank you. Fairly new to using serial so hopefully no more odd balls like this. I'd never had to consider the return being sent running things in a command window before.
My end state of this little endeavor will just be a load of variables coming in over serial from a program monitoring the contents of a file on the PC. Long way to go =)
Zarklin:
Forgive this basic question I tried searching first and could not find a solution. Thank you in advance.
In short I am doing a basic prompt over Serial monitor for a LED toggle. Setting the bool based on input and the led toggle function as intended.
However upon trying to do input validation in the form of an If else statement it appears to be executing the else statement every time. This is in addition to the above if or else if being true. In the case neither are valid the else executes twice.
Try this:
#include <Arduino.h>
bool LED;
const int LED_Pin = 12;
void setup() {
pinMode(LED_Pin, OUTPUT);
Serial.begin(9600);
while (! Serial); // Wait untilSerial is ready - Leonardo
Serial.println("Turn On LED? Y/N");
}
void loop() {
if (Serial.available())
{
String ch = Serial.readStringUntil(13);//Read the serial port until a hard return is encountered.
ch.toLowerCase();
if (ch.startsWith("y")) LED = true;
else if (ch.startsWith("n"))LED = false;
else Serial.println("Invalid Input\n\nTurn On LED? Y/N");
if (LED == true)
{
digitalWrite (LED_Pin, HIGH);
Serial.println("LED ON");
}
else
{
digitalWrite (LED_Pin, LOW);
Serial.println("LED OFF");
}
}
}
Make sure your serial monitor is configured to send LF/CR....
Mike