Analog Output – Fading LED

analog input

LEDs can be controlled with an analog value (from 0 to 255) instead of a simple LOW/HIGH.
To use outpus in analog mode you have to use an Arduino pin with the ~ sign next to it.

int ledPin = 13;    // LED connected to analog pin 9
 
void setup()  { 
  // nothing happens in setup 
} 
 
void loop()  { 
  // fade in from min to max in increments of 5 points:
  for(int fadeValue = 0 ; fadeValue < = 255; fadeValue +=5) { 
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);         
    // wait for 30 milliseconds to see the dimming effect    
    delay(50);                            
  } 
 
}

Exercise
Now reproduce the “breathing” standby led on Mac computers – slow fade in and fade out.

PWM: how does it work?

Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means. Digital control is used to create a square wave, a signal switched between on and off.

In this circuit:
0 = full color
255 = LED off

RGB LED

RGB LED are 3 LED in one. They either have a common anode or cathode so make sure to know which one you are using.

Schematics:

Breadboard circuit:

Make a color mixer using 3 potentiometers.

You may want to use a map function because an analog input ranges from 0 to 1023 while an analog output ranges from 0 to 255:

LEDvalue = map(potValue, 0, 1023, 0, 255);

Solution:

 
int RedLedPin = 11;    // LED connected to analog pin 11
int GreenLedPin = 10;    // LED connected to analog pin 10
int BlueLedPin = 9;    // LED connected to analog pin 9
 
int RedLedPot = 0;    // Pot connected to analog pin A0
int GreenLedPot = 1;    // Pot connected to analog pin A1
int BlueLedPot = 2;    // Pot connected to analog pin A2
 
void setup()  { 
 
} 
 
void loop()  { 
 
  int R = analogRead(RedLedPot);
  int G = analogRead(GreenLedPot);
  int B = analogRead(BlueLedPot);
 
  R = map(R, 0, 1023, 0, 255);
  G = map(G, 0, 1023, 0, 255);
  B = map(B, 0, 1023, 0, 255);
 
  analogWrite(RedLedPin, R);         
  analogWrite(GreenLedPin, G);         
  analogWrite(BlueLedPin, B);         
 
}
Posted in

Post a comment