Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 3 ■ COMMUNICATION PROTOCOLS

else
{
// Connection to server:port failed
Serial.println("[ERROR] Connection Failed");
}


Serial.println("-----------------------------------------------");
}


That is pretty much it for publishing data from your Arduino to a server.

Standard Functions


The code in the fourth and final section implements Arduino’s standard setup() and
loop() functions.
As Listing 3-4 shows, the setup() function initializes the serial port, connects to
Internet, and then makes either the HTTP GET request by calling doHttpGet() or the
HTTP POST request by calling the doHttpPost() function.


Listing 3-4. Code for Standard Arduino Functions—setup()


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


// Connect Arduino to internet
connectToInternet();


// Make HTTP GET request
doHttpGet();
}


Since in this project you are not doing any server-side processing with the data that
is being sent from sensor, you will add code to read response from the server to loop()
function. The test server that you are using simply echoes all the request information in
the response, so you are just going to read the response and print it to the Serial Monitor
window.
As provided in Listing 3-5 , check if there are any bytes available to be read from
WiFiClient , read all the available bytes, and print them to the Serial Monitor window.
Once all the bytes have been read and printed, stop the client.

Free download pdf