My code functions as intended and I'm getting an error in the serial monitor that is more of an annoyance than anything, but I still would like to figure out why it's happening.
The program is designed to switch between turning the brightness of an LED up or down ('2'), or to adjust the delay time between a blinking LED ('1'). The serial monitor asks which mode I would like to select, and if I select '2', the second if condition, the 'invalid choice' message from the else condition is displayed on the serial monitor, which is followed by the message from the 2nd if condition and the program functions as expected. Why is the message from the else condition popping up?
const byte pot = A1;
const int LED = 13;
int dt = 0;
String choice;
void setup(){
pinMode(LED, OUTPUT);
Serial.begin(9600);
Serial.println("Which function would you like to perform?");
Serial.println("1 for blink, 2 for brightness");
}
void loop() {
while (Serial.available() == 0){}
choice = Serial.readString();
if (choice == "1"){
Serial.println("Turn the pot to adjust the blinking speed");
while(Serial.available() == 0){
int val = analogRead(pot); // reads pot value and stores it
val = map(val, 0, 1023, 0, 255); // re-maps reading to 0-255
dt = val + 30; // adds 30ms so bottom range of dt still blinks
digitalWrite(LED, HIGH);
delay(dt);
digitalWrite(LED, LOW);
delay(dt);
}
}
if (choice == "2"){
Serial.println("Turn the pot to adjust brightness");
while (Serial.available() == 0) {
int val = analogRead(pot); // reads pot value and stores it
val = map(val, 0, 1023, 0, 255); // re-maps reading to 0-255
analogWrite(LED, val);
}
}
else {
digitalWrite(LED,LOW);
Serial.println("Invalid Choice. 1 for blink, 2 for brightness");
}
}