Arduino program structure and execution

In this section we will study the general structure of an Arduino sketch. After going through this section you will be able to understand the important parts of an Arduino sketch. This section will also explain how each part of an Arduino sketch gets executed in the Arduino development board.

Arduino C programs are called sketches. A basic sketch structure needs at least two functions in the program body. These functions are listed as follows:

  • setup()
  • loop()

These functions should always have a same name that is, setup() and loop(). The Arduino development board is pre-programed to execute a loaded sketch by looking for these two function names in the body of a sketch. So if these two function names are not present in the C sketch, then the Arduino IDE will not even compile the sketch successfully. Instead the following errors will be thrown:

  • undefined reference to `setup'
  • undefined reference to `loop'

The next figure shows a standard Arduino IDE window and C sketch, on a Windows 7 operating system based computer.

Figure 5: Arduino Sketch Basic Structure

You will notice that in the IDE there is a C sketch displayed on the screen. The distinct parts of the Arduino sketch have been highlighted with dotted lined rectangles. Usually, all Arduino sketches follow this same format, with at least these two basic functions: setup() and loop().

Now let us try to understand the basic structure further. The setup() function is executed once and only once, every time when the Arduino board is powered up. This function is automatically invoked by the Arduino board, only for the first time when the board is powered up. This is an ideal place to write all the code for one-time configuration of variables and I/O pins used in the sketch. In all the example sketches in this book you will notice that various input/output pins are configured appropriately in this setup() function.

Next comes the loop() function that keeps getting invoked infinitely by the Arduino board. Whatever you write in this loop() function will keep getting executed infinitely, until the power supply to the Arduino board is turned off or drained out. This function contains the main logic of the embedded program. This main logic can in turn invoke various user defined functions.

In case you are curious, the code shown in the preceding sketch is for a water level measurement device using an Ultrasonic distance measurement sensor. The use of sensors in general has been explained in the Chapter 4, Day 2 - Interfacing with Sensors in this book. An ultrasonic sensor has been used in the Chapter 6, Day 4 - Building a Standalone Device. While a sound detection sensor has been used in the Chapter 8, Day 6 - Using AC Powered Components.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.32.86