Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 1 ■ ARDUINO BASICS


Listing 1-1. Recommended Code Structure


/*



  • External Libraries
    */


#include <SPI.h>


/*



  • Constants & Variables
    */


char message[] = “Hello Internet of Things”; // Single line comment


/*



  • Custom & Standard Functions
    */


void printMessage()
{
Serial.println(message);
}


void setup()
{
// Initialize serial port
Serial.begin(9600);
}


void loop()
{
printMessage();
delay(5000);
}


Listing 1-1 consists of three functions. It has two standard Arduino functions,
called setup() and loop() , which are automatically called by Arduino once the code
is uploaded. They therefore must be present for the code to run. The third is a custom
function called printMessage() that simply prints a message to the Serial Monitor
window shown in Figure  1-6.
The setup() function is called only once. Initializations are done in this function
including serial monitor initialization using code Serial.begin(9600). The loop()
function, as the name suggests, runs in a continuous loop. Any post-initialization
processing such as reading sensor data can be done in this function. The loop() function
calls printMessage() function and then waits 5,000 milliseconds before repeating.

Free download pdf