Project 1.00 Blink

Nearly everyone starts by learning how to blink an LED. Let’s take a second to think about how a light blinks. First, a light turns on, then waits for some amount of time, then turns off, waits for some amount of time, and repeats. That process is what we need to create in Arduino code.

///////////////////////////////////////////////////
//Project 1.00 Blink

byte LED1 = 13;

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

void loop(){ 
  digitalWrite(LED1,HIGH); 
  delay(1000); 
  digitalWrite(LED1,LOW); 
  delay(1000);
}
///////////////////////////////////////////////////

*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.

Let’s take a closer look at how this sketch works. We declare one byte variable at the top of the sketch. It is a global variable since it is declared outside the setup() function, loop() function, or any other function. This means we can use it anywhere else in the sketch and it will be recognized. LED1 gets assigned the value 13 because that’s the pin number (on the microcontroller) that LED1 is connected to.

byte LED1 = 13;

 Every sketch needs one setup() and one loop() function. The setup() function runs only once. That’s all we need to set the pinMode of the LED to output so that we can switch it on and off:

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

Now comes the loop() function. This function will run repeatedly. At the top of the block comes the digitalWrite statement. This powers the pin attached to LED1 with 5 V, causing the LED to light up.

void loop(){ 
   digitalWrite(LED1,HIGH);

LED1 will remain in a HIGH state until we tell it otherwise or we disconnect the MC Trainer from its power source. We want it to stay on for only a second, so we wait 1000 milliseconds (1 second):

delay(1000);

And then switch the pin to LOW. Now the LED switches off:

digitalWrite(LED1,LOW);

We keep it off for another second and then finish the loop() function:

  delay(1000);
}

The closing bracket tells the MC Trainer to go back to the top of the loop() function and repeat it.

Try seeing how fast the LED can blink by changing the number in the delay function. Just a hint, it can blink faster than we can see!

Previous
Previous

Project 1.01 Blink x2