I am trying to get a constant PWM value from the PWM pin based on the user input. For example: the user hits 1, the output PWM 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 PWM goes to that value for about a second and then goes back to 0. Can you please let me know what I am missing?
// Sketch: Blinking two LEDs by user
int test_pin=2; // declare pin10 as ledpin
int PWMvalue; // 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
}
PWMvalue = Serial.parseInt(); //Read the data the user has input
if (PWMvalue==0)
{
analogWrite(test_pin,0);
}
else if (PWMvalue==1)
{
analogWrite(test_pin,100);
}
else if (PWMvalue==2)
{
analogWrite(test_pin,200);
}
else if (PWMvalue==3)
{
analogWrite(test_pin,300);
}
else if (PWMvalue==4)
{
analogWrite(test_pin,400);
}
else if (PWMvalue==5)
{
analogWrite(test_pin,500);
}
else if (PWMvalue==6)
{
analogWrite(test_pin,600);
}
else if (PWMvalue==7)
{
analogWrite(test_pin,700);
}
else if (PWMvalue==8)
{
analogWrite(test_pin,800);
}
else if (PWMvalue==9)
{
analogWrite(test_pin,900);
}
else
{
analogWrite(test_pin,1023);
}
Serial.print("The user has choosen the number:");
Serial.println(PWMvalue);
Serial.println(" ");
}
```
-
I am using Arduino MKR NB 1500. I am using PWM pin 2Dave– Dave2021年08月16日 18:02:47 +00:00Commented Aug 16, 2021 at 18:02
-
1set Line ends to none in Serial Monitor. line ending counts into available(). readInt waits one second for number, then it returns 0.Juraj– Juraj ♦2021年08月16日 18:04:07 +00:00Commented Aug 16, 2021 at 18:04
-
setting the line ends to none worked. Thanks Juraj!Dave– Dave2021年08月16日 19:27:15 +00:00Commented Aug 16, 2021 at 19:27
-
why have you not included the serial console printout?jsotola– jsotola2021年08月16日 19:45:10 +00:00Commented Aug 16, 2021 at 19:45
1 Answer 1
You wait for user input with a while (Serial.available() == 0)
, the you read the input with Serial.parseInt()
. parseInt will wait a second for digits. It will end on a non digit character or timeout and return the number corresponding to received digits. If no digits were received a 0 is returned.
Serial Monitor has Line end setting. If there is some line ending selected, it will send line ending character(s).
Your waiting loop while (Serial.available() == 0)
will end on line ending character which followed the number processed in previous loop. parseInt
will not find a digit so it times out after a second and returns a 0, which causes setting the PWM to 0.