Arduino LED brightness – Analog Basic

The Analog pins on the Arduino or DFR Romeo can be used to adjust the brightness of a LED.

The analog pin takes anything between 0 and 255. 0 means off, 255 means the brightest. Make sure you resist the voltage using a suitable resitor to preserve the LED life.

Connect the long leg of the LED to pin 9, and the short leg to a resistor before connecting it to ground.

Connect the three legs of a potentiometer to 3 pins.

Copy and paste the codes below and try it out.  

int ledPin = 9;      // LED connected to digital pin 9
int analogPin = 3;   // potentiometer connected to analog pin 3
int val = 0;         // variable to store the read valuevoid setup()
{
  pinMode(ledPin, OUTPUT);   // sets the pin as output
}

void loop()
{
  val = analogRead(analogPin);   // read the input pin
  analogWrite(ledPin, val / 4);  // analogRead values go from 0 to 1023, analogWrite values from 0 to 255
}

(Visited 250 times, 1 visits today)