Whats wrong with this code

Hi, I want to dim a LED using the pc. But the code does not seem to respond to what i send via serial.

Any advise.

const int ledPin = 9;      // the pin that the LED is attached to

void setup()
  // initialize the serial communication:
  // initialize the ledPin as an output:
  pinMode(ledPin, OUTPUT);

void loop() {
  byte brightness;

  // check if data has been sent from the computer:
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    brightness = Serial.read();
    // set the brightness of the LED:
    analogWrite(ledPin, brightness);

Could it be that whatever is sending to your Arduino is sending a 'newline' character (value=10) at the end of each line so your sketch is responding to that as the last thing sent?

Try putting a short (250 millisecond?) delay after the analogWrite() to see if the LED briefly switches to the value you send before switching back to 10.

Another way to test is to put a Serial.print(brightness) in your code just before the analogWrite(). That will echo back, in ascii decimal, the values your sketch is receiving. That way you can tell if what you receive matches what you think you are sending.

I think nothing is wrong with the code. Do you have a led and resistor to pin 9 ? The led to ground ?

To know what is going on, take a look at the analogWrite() function first. http://arduino.cc/en/Reference/analogWrite I requires a parameter from 0 to 255. That value is read with Serial.read().

So the only thing you have to do is send a byte (value 0 to 255) How will you send that ? For example if you would type 'A' followed by Enter and have CR (carriage return) and LF (newline) turned on. This is what you are sending: 'A' = 65 (0x41), CR = 13 (0x0D), LF = 10 (0x0A). So the led is set to a PWM value of 65, then 13, and at last at 10.


What do you want to type into the serial monitor, and how will you translate that into a PWM value of 0...255 ? If you want to type the string "120", you can take a look at Serial.parseInt(). http://arduino.cc/en/Serial/ParseInt

(while I was typing, johnwasser wrote the same)