Getting constant ADC value based on user input from serial monitor

I am trying to get a constant ADC value from the ADC based on the user input. For example: the user hits 1, the output ADC value is 100, if it is 2 the output would be 200. This will continue till the user enters a new number. The issue I am having with my code is when I enter a number, the output of the ADC goes to that value for about a second and then goes back to 0. Can you please let me know what I am missing?
I am using Arduino MKR NB 1500 board

// Sketch: Blinking two LEDs by user
int test_pin=2; // declare pin10 as ledpin
int ADCvalue; // variable to store the number of blinks
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  Serial.println("What is the new speed?"); //Prompt User for Input
 while (Serial.available() == 0) {
    // Wait for User to Input Data
  }
  ADCvalue = Serial.parseInt(); //Read the data the user has input
 
  if (ADCvalue==0)
  {
    analogWrite(test_pin,0);
    }
    else if (ADCvalue==1)
    {
      analogWrite(test_pin,100);
      }
      else if (ADCvalue==2)
    {
      analogWrite(test_pin,200);
      }
      else if (ADCvalue==3)
    {
      analogWrite(test_pin,300);
      }
      else if (ADCvalue==4)
    {
      analogWrite(test_pin,400);
      }
      else if (ADCvalue==5)
    {
      analogWrite(test_pin,500);
      }
      else if (ADCvalue==6)
    {
      analogWrite(test_pin,600);
      }
      else if (ADCvalue==7)
    {
      analogWrite(test_pin,700);
      }
      else if (ADCvalue==8)
    {
      analogWrite(test_pin,800);
      }
      else if (ADCvalue==9)
    {
      analogWrite(test_pin,900);
      }
      else 
    {
      analogWrite(test_pin,1023);
      }
      
  Serial.print("The user has choosen the number:");
  Serial.println(ADCvalue);
  Serial.println(" ");
}

Serial monitor line ending to "none"

1 Like

An alternative that allows for line ending characters is to flush the input buffer before prompting for input:

  while (Serial.available()) Serial.read();  // <<< Add this line
  Serial.println("What is the new speed?"); //Prompt User for Input
  while (Serial.available() == 0) {
    // Wait for User to Input Data
  }
  ADCvalue = Serial.parseInt(); //Read the data the user has input
1 Like

1 Like

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