06) Blinking Light

Alright, now lets make it blink.
For this example I will be using the function called "delay()", where as normally I would not like to use this function. However this function is very easy to use, and especially to starting programmers.

delay only uses one argument, milliseconds of waiting time. (NOTE: 1000 milliseconds = 1 second)

so when we start writing the program, we will get something like this:

void setup()
{
}

void loop()
{
  digitalWrite(5,HIGH);
  delay(1000);
  digitalWrite(5,LOW);
}
So upload it to the board.

You should get a non-blinking light. Not what we wanted yes? This process of solving problems in code is called de-bugging. There is no real bug in the Arduino, but in the old days when they used analog computers, bugs used to land on the circuits and cause strange values. They would have to remove the bugs of the circuitry to fix the problem. But even though we do not have that problem today, the term is still in use.
If we look at the code in more of an understandable format, we get this:
Turn on light
Wait 1 second (1000 milliseconds)
Turn off light

And when the program loops, it gets this:
Turn on light
Wait 1 second (1000 milliseconds)
Turn off light
Turn on light
Wait 1 second (1000 milliseconds)
Turn off light
Turn on light
Wait 1 second (1000 milliseconds)
Turn off light

You might have noticed that there is no delay from the off to the on transition! This is in fact a really common mistake. A lot of programmers make little mistakes that could be frustrating to fix, but eventually realize that it was a very easy fix.
The new program will look something like:

void setup()
{
}

void loop()
{
  digitalWrite(5,HIGH);//Turn light on
  delay(1000);//Wait one second
  digitalWrite(5,LOW);//Turn light off
  delay(1000);//Wait one second
}
Then upload it. The light should now blink as we intended. Congratulations!
Comments