Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 4 ■ COMPLEX FLOWS: NODE-RED


Internet Connectivity (Wireless)


The second section of the code defines variables, constants and functions that are going
to be used for connecting to the Internet. Use the code from Listings 2-7 , 2-8 , and 2-9
(Chapter 2 ) here.


Read Sensor Data


The third section of the code is provided in Listing 4-4. It defines variables, constants, and
functions that are going to be used for reading sensor data.
The readSensorData() function reads data from Analog Pin A0, and the result is
between 0 and 1023. The greater the value returned, the brighter the light source. The
light sensor value is assigned to the lightValue variable.


Listing 4-4. Code for the Reading Light Sensor Data


int lightValue;


void readSensorData()
{
//Read Light Sensor Value
lightValue = analogRead(A0);


Serial.print("[INFO] Light Sensor Reading: ");
Serial.println(lightValue);
}


Data Publish


The fourth section of the code is provided in Listing 4-5. It defines variables, constants,
and functions that are going to be used for creating and sending an HTTP request to the
server. This code is a slightly modified version of the HTTP GET that you developed in
Chapter 3.
The main modification in this code is its ability to open and close a connection to
the server repeatedly. Apart from that, make sure to change the server and port values to
your Node-RED server’s values. The other changes include passing a lightValue variable
in the request and invoking the /lightSensorTweet URL.


Listing 4-5. Code for Starting the Node-RED Flow Using HTTP Request


//IP address of the HTTP server
char server[] = { "10.0.0.6" };
int port = 1880 ;


unsigned long lastConnectionTime s= 0;
const unsigned long postingInterval = 10L * 1000L;

Free download pdf