\(\require{color}\)

Arduino Basics: Blink an LED

December 4th, 2015


The first thing everyone should know is that in most simple C++ cases, such as coding basic Arduino programs, Java knowledge is more satisfactory. I have never coded in C++ other than for Arduino. I code mostly websites (this blog included), and as a result, I know primarily HTML, PHP, SQL, and Javascript. I have coded an Android app, so I know a bit of Java, too. Coding in C++ on a basic level is very similar to coding in Java, so I had no problem picking up the syntax of the Arduino coding environment.

The main thing to understand about Arduino code is that it has two main parts: The LOOP and the SETUP.

The SETUP is where most of the variables get initialized, and you define your pin values and such. The setup is used for initial declarations and statements that will be used later, in the loop. For example, to blink an LED pin, we need only define the output pin once, so it is advisable to define the pin inside the setup.

The LOOP gets run continuously (well, sort of) and continues to execute until the power is turned off or the loop is broken. Let’s build on the previous example, where we want to blink an LED. We initialized the pin in the setup statement, but if we try to toggle the LED on and off using the setup, we won’t be able to, as the setup runs only once. Well, okay, we could write a bunch of statements in a row to toggle the LED, but this would be very, very lengthy and defeat the whole principle of the ease of using the loop. So, let’s see how we could make the LED blink using the loop…

The loop, well, loops, essentially infinitely quickly for the purposes of this particular exercise, so we can ignore any timing delays. We need switch the LED on and off after a certain amount of time, and repeat the process. Let’s say we want the led to stay on for one second, then turn off for one second. We need to toggle on, delay one second, then toggle off, and we can’t forget to delay again before the next cycle. If we forget to delay at the end, it will toggle on, then wait a second, then toggle off, and then it will instantly toggle back on. It is crucial to remember to delay at the end. Our loop code should look something like this…

 

toggle();
delay(1000); //milliseconds
toggle();
delay(1000);

The loop will loop through this code until we tell it to stop.

Hope you enjoyed this basic Arduino lesson.

Author

Software

Links


Leave a Reply

Your email address will not be published. Required fields are marked *