I am trying to get the serial monitor to prompt me to input two settings - the PWM level and the Resonance level. I am being prompted to input the PWM level, but before I can input the Resonance level it is set to zero and then I am asked again for the PWM level.

I am using Serial.flush(); inbetween the commands to clear the serial input, but I still cannot input the Resonance level before it is set to zero.

Here is my code:

int PWMPin = 10;       // Pin 10 connects to MOSFET gate on breadboard 
int ResPin = 4;        // Pin for the resonator stage 

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);   // Define baud rate for console to be 9600
  pinMode(PWMPin, OUTPUT);  
  pinMode(ResPin, OUTPUT);   


void loop() {
  // put your main code here, to run repeatedly:

Serial.println("What PWM level do you want to test?");   // Testing only  
 while (Serial.available() == 0) {
     // Wait for user input
  int test_level_PWM = Serial.parseInt();
    analogWrite(PWMPin, test_level_PWM);
    Serial.print("PWM Level: ");

Serial.println("What Resonance level do you want to test?");    
 while (Serial.available() == 0) {
     // Wait for user input
  int test_level = Serial.parseInt();
    analogWrite(ResPin, test_level);
    Serial.print("Resonance Level: ");


Here is the serial monitor output. I was able to input the PWM level but the Resonance level was set to zero immediately after and then I was asked to input the PWM level again.

enter image description here

  • I would consider restructuring this into a state machine with (something like) "input" and "run" states. I'd also reconsider using parseInt because its default timeout of 1s can lead to unexpected behavior; might just want to handle that manually. Jul 2, 2021 at 13:59
  • 1
    Serial.flush() doesn't do what you think. the line end characters will be still in the RX buffer. flush() waits for TX buffer to be send. arduino.cc/reference/en/language/functions/communication/serial/…
    – Juraj
    Jul 2, 2021 at 15:16
  • in the serial monitor, in place of new line ending, select no line ending. After making this change, your code worked on my system.
    Nov 14, 2022 at 8:21

1 Answer 1


Your line


is probably intended to remove additional input after the expected numerical input. But that's not what it's doing. (See @jurai's comment)

Either avoid additional input like NewLine characters, or remove them using something like

while (Serial.available()) {delay(1); Serial.read();}

( The delay(1); takes care of slowly coming in serial data at 9600 Baud )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.