2

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);
}
VE7JRO
2,51519 gold badges27 silver badges29 bronze badges
asked Aug 18, 2019 at 19:50

1 Answer 1

3

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.

answered Aug 18, 2019 at 19:53
1
  • 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. Commented Aug 19, 2019 at 6:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.