Categories

Fading LED

Connect an LED to digital pin 3

Code

void setup()
{
pinMode(3, OUTPUT);
}

void loop()
{
for (int a = 0 ; a < 256 ; a++)
{
analogWrite(3, a);
delay(5);
}
for (int a = 255 ; a >= 0 ; a--)
{
analogWrite(3, a);
delay(5);
}
delay(200);
}
Share

Flash an LED

The ability to flash an LED is the most basic ‘hello world’ type of program you can write and run on your arduino.

Most Arduino’s have an LED attached to D13, rather than take the easy option we will attach an LED externally to the Arduino, if you wish to flash the LED on the board skip to the code and then change the led value as explained at the end of the article

Parts List

Here are the parts you will require

1 Arduino UNO or equivalent
1 LED
1 470 ohm resistor

1 Breadboard to build the circuit
Wires to connect the LED resistor to the Arduino

Here is what you will build, watch the polarity of the LED, the image below shows how to tell the positive (anode) and negative (cathode) apart.

LED polarity

LED polarity

As you can see the cathode is connected to the GND on the Arduino.

LED breadboard layout

LED breadboard layout

Schematic

Here is the schematic, fairly straightforward

LED and arduino schematic

LED and arduino schematic

 

We will toggle the appropriate Arduino output pin high to switch the LED on, to switch it off we will toggle the output low.

Code

Here is the code, we have ‘over commented’ so you can see what is going on here

int ledPin = 2; // we will use this variable later

// The setup() method runs once at startup
void setup()
{
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
}

// the loop() method repeats indefinitely
void loop()
{
digitalWrite(ledPin, HIGH); //switch LED on – high
delay(1000); //delay for 100 ms
digitalWrite(ledPin, LOW); //switch LED off – low
delay(1000); //delay for 100 ms
}

Incidentally if you wish to switch the LED on the board on and off changeĀ int ledPin value to 13

 

Share