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(test_level_PWM);
Serial.flush();
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: ");
Serial.println(test_level);
delay(1000);
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.
parseInt
because its default timeout of 1s can lead to unexpected behavior; might just want to handle that manually.