Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 8 ■ IOT PATTERNS: WEB APPS


Listing 8-7. Code for Reading Temperatures


int TEMP_SENSOR_PIN = A0;


float temperatureC = 0.0;
float temperatureF = 0.0;


void readSensorData()
{
//Read Temperature Sensor Value
int temperatureSensorValue = analogRead(TEMP_SENSOR_PIN);


float voltage = temperatureSensorValue * 5.0 / 1024;


//Converting reading to Celsius
temperatureC = (voltage - 0.5) * 100;


//Converting reading to Fahrenheit
temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;


//Log Sensor Data on Serial Monitor
Serial.print("[INFO] Temperature Sensor Reading (F): ");
Serial.println(temperatureF);
}


Data Publish


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


Listing 8-8. 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;

Free download pdf