user58904: 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:
  Serial.begin(9600);
  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: ");
  Serial.println(pwm);
  delay(1000);

}


user4143: 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.

Reading Serial on the Arduino


58904: <p>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. <strong>Any idea why this is occurring?</strong>
</p>

<pre class="lang-cpp prettyprint-override"><code>int ledpin1 = 3;
int pwm = 0;

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

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

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

}
</code></pre>
 4143: <p>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).</p>

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

<p>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.</p>

<ul>
<li><a href="https://majenko.co.uk/blog/reading-serial-arduino" rel="nofollow noreferrer">Reading Serial on the Arduino</a></li>
</ul>
