Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 12 ■ IOT PLATFORMS


Listing 12-1. Code for Including External Dependencies


#include <SPI.h>
#include <WiFi.h>
#include <HttpClient.h>;
#include <Xively.h>;


Internet Connectivity (Wireless)


The second section of the code defines the 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 12-2. It defines the variables,
constants, and functions that are going to be used for reading the sensor data.
The readSensorData() function reads data from Analog Pin A0 and the result is
between 0 and 1023. Higher values correspond to lower soil moisture levels.


Listing 12-2. Code for Reading Soil Moisture Sensor Value


int MOISTURE_SENSOR_PIN = A0;
float moistureSensorValue = 0.0;


void readSensorData()
{
//Read Moisture Sensor Value
moistureSensorValue = analogRead(MOISTURE_SENSOR_PIN);


//Display Readings
Serial.print("[INFO] Moisture Sensor Reading: ");
Serial.println(moistureSensorValue);
}


Data Publish


The fourth section of the code defines the variables, constants, and functions that are
going to be used for publishing sensor data to the Xively channel.
In order to communicate with Xively, you need to provide the Feed ID and API key
that were generated after you completed device setup in Xively. Both of these keys are
unique to you. You will also need to provide the exact channel name that you entered in
Xively. If the API key or Feed ID are incorrect, your device will not be able to connect with
your Xively account, and if the channel name is incorrect, the data will not show up in the
correct graph on the Xively dashboard. All these values have been highlighted in the code
(see Listing 12-3 ).

Free download pdf