Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 7 ■ IOT PATTERNS: ON-DEMAND CLIENTS

// Distance Calculation
float distance = pulseIn(ECHOPIN, HIGH);


Serial.println("[INFO] Object Distance: " + String(distance));


if(distance < 500)
{
Serial.println("[INFO] Parking Spot Occupied");


// Publish sensor data to server
publishSensorData("OCCUPIED");
}
else
{
Serial.println("[INFO] Parking Spot Open");


// Publish sensor data to server
publishSensorData("OPEN");
}
}


Data Publish


The fourth section of the code, as provided in Listing 7-7 , defines the 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 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 PHP server’s values. Make sure to change the server , port , and requestData
variables and the URL values.


Listing 7-7. Code for Sending an HTTP Request


//IP address of the server
char server[] = { "bookapps.codifythings.com" };
int port = 80 ;


unsigned long lastConnectionTime = 0;


const unsigned long postingInterval = 10L * 1000L;


void publishSensorData(String updateParkingSpot)
{
// Read all incoming data (if any)
while (client.available())
{

Free download pdf