I am trying to write to serial to control the brightness of an LED. When I initially type in a value such as '50' or '100', the LED lights up, but then the 'ppm' value drops down to '10' and just stays there (regardless of what I enter in initially. Any idea why this is occurring?

int ledpin1 = 3;
int pwm = 0;

void setup() {
  // initialize serial communication at 9600 bits per second:
  pinMode(ledpin1, OUTPUT);

// the loop routine runs over and over again forever:
void loop() {
  // reads input to serial monitor
  if (Serial.available() > 0) {
    pwm = Serial.read();

  analogWrite(ledpin1, pwm);
  Serial.print("PWM value is: ");


When you type "100" you aren't sending the number 100. You're sending the characters "1", "0", "0", and whatever selected line ending you have (CR, LF, or CR and LF).

So if you have CR+LF for your line ending you're reading the numbers 49, 48, 48, 13 then 10.

You need to read the characters as they arrive and group them into a representation of the number (up until you get the line ending), then convert that representation into an actual number.

| improve this answer | |
  • 1
    "You need to read the characters ..., then convert that representation into an actual number." - Or send just a single byte of value 100 over the serial port, effectively moving the conversion from the arduino to the PC. Which is more appropriate depends on the situation. – marcelm Aug 19 '19 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.