Arduino recieves unwanted zeros from serial port

Hello, this is my first post here, and I'm a beginner at microcontroller programming and really electronics in general. I've been wanting to try my hand at some serial communication. I have encountered a problem I couldn't figure out by myself, or come up with the correct search phrase in case this has already been discussed. :slight_smile:
Anyway, I have the Arduino UNO, and I'm running this simple program, wich fades a LED based on input from serial monitor:

const int ledPin = 10;

void setup()
{
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);  
}

void loop()
{
   int brightness;
  
   if (Serial.available())
   {
     brightness = Serial.parseInt();
     Serial.println(brightness);
     
     analogWrite(ledPin, brightness);
   } 
}

Here's what happens when I run this.

1 - I send a value between 0-127 from the serial monitor
2 - as the value is sent, TX and RX flashes briefly, the sent value comes up on serial monitor and the LED is lit up/faded down accordingly
3 - after a second or so - and here's the problem - Without any user input, only TX flashes , serial monitor outputs a '0', and the LED turs off
4- repeat from 1, exactly the same procedure.

If Anyone could explain to me what's going on here. Is this some standard thing I've missed? local pc behaviour? problematic code?

Thanks in advance!

/p

Simplify a lttle - try

brightness = Serial.read();

instead of

brightness = Serial.parseInt();

You do have a current limit resistor on the LED pin?

When using the serial monitor, what option have you selected in the lower, right corner? The parseInt() function looks for the first character that is NOT a digit. When it encounters that digit, it stops reading. But, it doesn't remove that value from the serial buffer.

So, that character is still in the buffer, so there is still data to read, but there are no digits, so, parseInt() returns 0.

After the call to parseInt(), you need to peek(), and read() any non-digit characters still in the buffer, so Serial.available() returns 0.