Blinking LED

         The first program every programmer learns consists in writing enough code to make their code show the sentence "Hello World!" on a screen. The blinking LED is the "Hello World!" of physical computing.

LEDs

An LED is a small light (it stands for "light emitting diode") that works with relatively little power. The Arduino board has one built-in on digital pin 13.

Code

To blink the LED takes only a few lines of code. The first thing we do is define a variable that will hold the number of the pin that the LED is connected to. We don't have to do this (we could just use the pin number throughout the code) but it makes it easier to change to a different pin. We use an integer variable (called an int).

int ledPin = 13;

The second thing we need to do is configure as an output the pin connected to the LED. We do this with a call to the pinMode() function, inside of the sketch's setup() function:

void setup()
{
  pinMode(ledPin, OUTPUT);


Finally, we have to turn the LED on and off with the sketch's loop() function. We do this with two calls to the digitalWrite() function, one with HIGH to turn the LED on and one with LOW to turn the LED off. If we simply alternated calls to these two functions, the LED would turn on and off too quickly for us to see, so we add two calls to delay() to slow things down. The delay function works with milliseconds, so we pass it 1000 to pause for a second.

void loop()
{
  digitalWrite(ledPin, HIGH);
  delay(1000);
  digitalWrite(ledPin, LOW);
  delay(1000);


Upload the sketch to the board and you should see the on-board LED begin to blink: on for one second, off for the next.

Connecting an LED

LEDs have polarity, which means they will only light up if you orient the legs properly. The long leg is typically positive, and should connect to a digital pin on the Arduino board. The short leg goes to GND; the bulb of the LED will also typically have a flat edge on this side.

In order to protect the LED, you will also need use a resistor "in series" with the LED.

If the LED doesn't light up, trying reversing the legs (you won't hurt the LED if you plug it in backwards for a short period of time).

Full Sketch

int ledPin = 13;

void setup()
{
  pinMode(ledPin, OUTPUT);

void loop()
{
  digitalWrite(ledPin, HIGH);
  delay(1000);
  digitalWrite(ledPin, LOW);
  delay(1000);


BY
        REGU RAM SV.

1 تعليقات

إرسال تعليق

أحدث أقدم