I've been learning how to use the Arduino for 3 days following YT tutorials. I'm currently learning about Input-Output with the serial monitor.
After running the loop once, the serial monitor automatically inputs a 0 and is registered as an input then goes back to accepting user input.
Screenshot of what I mean:
Below is the code:
//inputs
int blinks;
String question = "How many times would you like the LED to blink? ";
//LED
int LEDPin = 8;
//while loop
int i = 1;
//delay
int delayTime = 500;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print(question);
//this waits for an input <while serial is empty>
while (Serial.available() == 0) {
};
//this reads the input
blinks = Serial.parseInt();
Serial.println(blinks);
//output
while (i <= blinks) {
digitalWrite(LEDPin, HIGH);
delay(delayTime);
digitalWrite(LEDPin, LOW);
delay(delayTime);
Serial.println(i);
i++;
};
i = 1;
}
I believe that the Serial Port might be reading the null terminator ('\0') or some garbage is left in the input buffer.
Use
Serial.flush()
after your while loop and see if that solves your problem.EDIT: I forgot to mention that I would suggest using
SerialEvent()
(read this) instead of checking for the serial input in your main loop. This approach is more reliable as it is based on interrupts.Keep on learning!