Help LED dim

I have a piece of code. I am forcing the LED to turn of when serial input == 0. But besides that, I want the brightness to equeal the value that is being send over the serial communication. I have spend hours on this. Please help.

int ledPin = 10;
int brightness = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() 
{
  int brightness = 0;

  if (Serial.available()) 
  { 
    brightness = Serial.read();
    
    if (brightness == '0')
    {
      digitalWrite(ledPin, LOW);
    }
    else
    {
     digitalWrite(ledPin, brightness);     
    }
  }
}

You should use a Rx buffer then take for example Rxbuffer[1] to be the value of your brightness.

Rxbuffer[0] = Start delimiter //0x7E
Rxbuffer[1]=Value
Rxbuffer[2]=END //Checksum

This mean send an array, receive an array.

What is sending value to your arduino?

Always use If serial availble>= VALUE

     digitalWrite(ledPin, brightness);

Does it work any better if you use analogWrite here? :slight_smile:

-br

What's the format of your serial input data, and where's it coming from?

Before messing around with serial input, take a look at the [u]Fade Example[/u] and learn how to adjust the brightness under program control first. (Hint - You can't dim with a digital write or a digital output... unless you create your own PWM.)

Then, maybe try an experiment where you write-in a brightness value, assign it to a variable, and then use and Serial.print to make sure your variable has the value you expect, and that the variable is between 0 and 255 as required for PWM dimming.

When you combine those two functions, your program should work.