Question on Serial Input

I am programming a potentiometer, and I got into a trouble while programming the input from Serial monitor. This is part of the code I have, that is supposed to display the prompt "Input the desired amplitude, 0 to 150V: ", and when the user enters a value, it reads and stores the value in the int amp. However, when I run this code, the serial monitor displays
"Input the desired amplitude, 0 to 150V: (amp)V"
"Input the desired amplitude, 0 to 150V: 0V".
Why is the extra second line with 0 appearing?

//amplitude is in V
int amp = 0;
unsigned int wait = 0;
void setup() {
  Serial.begin(9600);
}

void loop() {
  //voltage input
  Serial.print("Input the desired amplitude, 0 to 150V: ");
  wait = 1;
  while(wait){
    if(Serial.available()>0){
      wait = 0;
      Serial.begin(9600);
      amp = Serial.parseInt();
      Serial.print(amp);
      Serial.println("V");
    }
  }
  Serial.flush();
  delay(100);
}

Why do you have this in the loop?

You might still have invisible characters in the incoming buffer after the parseInt (flush is useless)

What end marker are you using in the serial monitor

You might try a Serial.flush() at the end of setup() just in case there are spurious characters present.

And, remove the Serial.begin(9600) from your loop() as suggested.

Add a small delay after the call to begin() in the setup as opening the serial monitor reboots the arduino so don’t print right away or you might see

ParseInt will also timeout so you’ll get pinged for input when the timeout strikes (1s default)

I would suggest to study Serial Input Basics to handle this text input asynchronously

I solved it. Somehow I didn't notice the Serial.begin(9600) in the loop. Deleted it, and seemed like I can change the Serial monitor setting to not make it send '\n' after an input, and that solved the issue. Thank you for your help.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.