IBM Watson IoT Platform

Introduction

The MediaTek LinkIt Smart 7688 Duo development board supports Wi-Fi communication in station and access point (AP) modes. It also provides interfaces for sensor connectivity. The data acquired from sensors can be transmitted conveniently using the Message Queuing Telemetry Transport (MQTT) protocol on a regular schedule to the IBM IoT Foundation or IBM Watson IoT platform and graphed, using capabilities in IBM Watson IoT platform. The IoT platform enables monitoring the real-time data remotely.

In this tutorial you’ll implement network and cloud connectivity operations in the Arduino environment, illustrating data acquisition from a sensor using the Arduino Yun Bridge with LinkIt Smart 7688 Duo development platform.

This tutorial guides you through:

  • Building the prototype, with details of the hardware requirements and how to put them together.
  • Creating the software to provide the interfaces with the sensor to collect the data and implement data communications to send that data to the IBM Watson IoT platform.
  • Running the software and graphing real-time temperature and humidity data on the cloud services.

At the end of the tutorial there are details on where to go for additional information on the LinkIt Smart 7688 Duo development board and how to create software for it.

Before you start

If you haven’t built a LinkIt Smart 7688 Duo project before using Arduino IDE, this section describes the steps you need to follow before commencing this project.

Install the development software

Full details on setting up the necessary LinkIt Smart 7688 Duo development environment can be found in get started with the LinkIt Smart 7688 Duo development board. Complete this before you continue, if you haven’t already set up your development environment.

Third-party software

This tutorial uses PuTTy, a secure shell (SSH) and telnet client, developed for the Windows platform. The communication with the IBM IoT platform is implemented using MQTT protocol, a lightweight, fast communications protocol designed for the IoT. The project development requires downloading and installing the Arduino MQTT libraries (see Additional libraries).

Building your project's hardware

This section describes the hardware and electronics needed to build your sensor data acquisition and transmission hardware and provides details on how to put them together.

What you need

To build the project’s hardware, in addition to a LinkIt Smart 7688 Duo development board, you need the following components:

ComponentDescriptionSource
SensorDHT temperature and humidity sensorSeeed Bazaar
CableMicro-USB cable 
Breakout boardA Grove breakout board for LinkIt Smart 7688 Duo.Seeed Bazaar

Note: the board is equipped with an onboard Wi-Fi antenna. To enable the I-PEX connector for external antenna connectivity, follow the instructions at section 2.2.4, “Antenna” in the LinkIt Smart 7688 developer’s guide.

Putting the components together

This section provides step-by-step instructions on putting the tutorial’s hardware together.

Step 1– Breakout board

Attach the LinkIt Smart 7688 Duo development board to the Grove breakout board.

Step 2 – DHT sensor

Attach the temperature and humidity sensor to the development board using Grove – Universal 4-pin buckled cable to the pin 4. The final hardware setup is:

Hardware setup of the project

Setup the board

In this project you’ll be using the development board in Wi-Fi station mode. By default, the development board is in AP mode. Change the configuration according to this guide.

Create your project's software

Your project needs an Arduino sketch to share data from the DHT sensor with IBM IoT platform. This section describes the software required as follows:

  • Additional libraries or components.
  • Overview of the Arduino sketch.
  • Transmitting sensor data to IBM Watson IoT platform.

Additional libraries

Add Arduino Yun Bridge library

To create the sensor data acquisition and transmission software you’ll be making use of Arduino Yun Bridge library. To enable the library, follow this guide: Working as an Arduino Yun. The summary of steps is shown below:

  1. Launch PuTTy and connect to the LinkIt Smart 7688 SSH console.
  2. Enter the commands below from the SSH console to enable the Arduino Yun Bridge.

    uci set yunbridge.config.enabled=’0’
    uci set commit
    reboot

    The Yun Bridge library is now successfully enabled.

Add DHT sensor library 

The project also requires DHT library that you can download from here and add under the libraries directory of your Arduino IDE. Restart the IDE before continuing.

Add Arduino MQTT client library 

In addition to the Yun Bridge library, the project requires MQTT client support in the Arduino IDE. The library is found here.

To integrate the library into your Arduino IDE:

  1. Download and extract the content of the latest version of the Arduino MQTT client from its GitHub repository.
  2. Copy the folder (PubSubClient) to the libraries directory of your Arduino IDE. Restart the IDE before continuing.

To test and verify the operation of the MQTT client you can download Mosquitto, a lightweight server implementation of the MQTT and MQTT-SN protocols.

You now have all required libraries to start implementing the project.

Overview of the Arduino Sketch

The content of a sketch is as follows:

  • Definitions of header files.
  • Definitions variables.
  • setup() function that initializes the resources for Arduino Yun bridge and serial communication.
  • loop() function that continuously listens to and processes events from hardware and software modules. The loop()function runs forever — until the device is shutdown.

Start your Arduino project

Before you can write the code for your sketch you need to create it, which is achieved as follows:

  1. Open Arduino IDE and by default a new sketch is created and displayed.
  2. Create a folder named DHTSensorBluemix in your documents folder and on the File menu click Save As navigate to the selected folder, name the sketch DHTSensorBluemix.ino and save it.

Add the header files for the supporting libraries

The first part of your code adds the libraries required to the DHTSensorBluemix.ino Arduino sketch.

Serial Peripheral Interface (SPI) communication

Add the SPI communication header file, from the Arduino SPI library.

 #include <SPI.h>

Arduino Yun Bridge communication

Add the Arduino Yun Bridge communication header file; see Additional libraries on how to enable the Yun Bridge.

#include <YunClient.h>

The MQTT library

Add the MQTT library communication header file; see Add Arduino MQTT client library.

#include <PubSubClient.h> 

I2C/TWI communication

Add the I2C/TWI communication header file, from the Arduino Wire library.

#include <Wire.h> 

Sensor communication

Add DHT temperature and humidity sensor installed in Add DHT sensor library.

#include <dht.h> 

Define the variables

Next the static variables used in the sketch are defined.

  1. DHT22_PIN to match the GPIO pin 4 to read values from the attached sensor at a specified pin.

    #define DHT22_PIN 4 
  2. MAC address of your device.

     char macstr[] = "your device’s MAC address";  // Enter the device MAC address here
  3. Communication parameters for the IBM Watson IoT platform, such as the server, the client and the topic.

    char servername[] = "quickstart.messaging.internetofthings.ibmcloud.com";
    String clientName = String("d:quickstart:arduino:") + macstr; 
    String topicName = String("iot-2/evt/status/fmt/json");
  4. Temperature and humidity parameters.

    float tempC = 0.0;
    float humidity = 0.0;
  5. An object of the class DHT.

    dht DHT;
  6. An object of the class YunClient for the Yun bridge communication.

     YunClient wifiClient;
  7. Define client method of type PubSubClient where the input parameters of the client method include.

     PubSubClient client(servername, 1883, 0, wifiClient);

Define the setup() function

Now the setup() function can be defined, to start the various services that will be used by the sketch.

  1. Initiate the bridge communication by calling the begin() method of the Bridge class.
  2. Initiate Serial communication with a baud rate of 9600 by calling the begin() method of the Serial class.

void setup()
{
   // Start the Yun Bridge
   Bridge.begin();    
   Serial.begin(9600); 
}

Add the loop() function 

The loop() function is executed continuously providing formatted temperature and humidity data and communication with IBM IoT platform. The details are described below. 

  1. Convert the client and topic names into character arrays and store in the clientStr and topicStr.

    char clientStr[34];
    clientName.toCharArray(clientStr,34);
    char topicStr[26];
    topicName.toCharArray(topicStr,26);
  2. Read the temperature and humidity data from the DHT sensor in a user defined function.

    getData();
  3. Connect to the server. In an if statement verify if the client is connected, if it isn't, print messages to the serial output by calling the print and println() methods of the Serial class, as follows.

     if (!client.connected()) {
        Serial.print("Trying to connect to: ");
        Serial.println(clientStr);   
        Serial.println("Connecting to server ");
    In a while loop verify if the client is connected to the clientStr, if not, call println() method of the Serial class to print out "Re-Connecting to server" message to the serial output. Repeat the operation for each 3 seconds by calling the delay(3000) function.

     while (! client.connect(clientStr))
        {
          Serial.println("Re-Connecting to server");
          delay(3000);
        }
    Once the connection is successfully established print out “Connected to the server” message to the serial output and exit the “if” statement.

     Serial.println("Connected to server");
  4. Send the formatted result to the server. In an "if" statement verify if the client is connected, if it is, send a message "Connected to server : Building jason" to the serial output by calling the println() method of the Serial class, as follows.

    if(client.connected() ) {
        Serial.println("Connected to server : Building jason");

    Assign a user defined buildJson() function to json variable of type String and then convert the string into a character array stored in the jsonStr of maximum length of 200.

    String json = buildJson();
    char jsonStr[200];
    json.toCharArray(jsonStr,200);

    Begin publishing to the server. Send "Connected to server : publishing" message to the serial output by calling the println() method of the Serial class. Then call the publish() method of the client with topicStr and jsonStr as input parameters and store the result in the pubresult of type boolean.

    Serial.println("Connected to server : publishing");
    boolean pubresult = client.publish(topicStr,jsonStr);
    Serial.print("attempt to send ");
    Serial.println(jsonStr);
    Serial.print("to ");
    Serial.println(topicStr);

    If pubresult is true, the data is successfully published, otherwise an error occurred. If the client isn't connected, print out “not yet connected” to the serial output and attempt to connect for each 5 seconds as defined in the delay(5000) function.

    if(pubresult)
         Serial.println("successfully sent");
        else
          Serial.println("unsuccessfully sent");
      }
      elseSerial.println("not Yet connected");
      
      delay(5000);
    }

User-defined functions

The functions getData() and buildJson() are user defined functions that will be described in this section.

Function getData()

This function simply checks the status of the data from the DHT22 library, then reads off the sensor data values if it is ready; otherwise, it prints out an informational message on the serial output. Call read22() method of the DHT class to read temperature and humidity data from a given pin and store the result in chk variable of type integer.

 int chk = DHT.read22(DHT22_PIN);

If the data is successfully read, assign 
tempc and humidity variables to appropriate values form the DHT sensor and print out to the serial output, otherwise, send and error message and reset the tempc and humidity, as follows.

if(chk == DHTLIB_OK)
    {
        Serial.println("------------------------------");
 
        tempC = DHT.temperature; 
        humidity = DHT.humidity;
       
         
        Serial.print("temperature = ");
        Serial.println(tempC);
        Serial.print("humidity = ");
        Serial.println(humidity);
    }
    else
    {
         Serial.print("Sensor Error: Temperature Read FAILED !!");
         // Setting the temperature and humidity values to ZERO. !!
         tempC = 0.0; 
         humidity = 0.0;
    }
     
}

Function buildJson()

Format the JSON output for temperature and humidity data.

 String data = "{";
  data+="\n";
  data+= "\"d\": {";
  data+="\n";
  data+="\"Device\": \"LinkIt Smart 7688 Duo DHT\",";
  data+="\n";
  data+="\"temperature (C)\": ";
  data+=(int)tempC;
  data+= ",";
  data+="\n";
  data+="\"humidity\": ";
  data+=(int)humidity;
  data+="\n";
  data+="}";
  data+="\n";
  data+="}";
  return data;

Full source code

The full source code of the project is shown below.

#include <SPI.h>
#include <YunClient.h>
#include <PubSubClient.h>
#include <Wire.h>
 
// This sketch uses DHT library from github : https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib
// You can download DHT library from the above link and add the library to Arduino IDE.
#include <dht.h>
#define DHT22_PIN 4
 
 
char macstr[] = "your device’s MAC address";  // Enter the device mac address here
 
char servername[] = "quickstart.messaging.internetofthings.ibmcloud.com";
String clientName = String("d:quickstart:arduino:") + macstr; 
String topicName = String("iot-2/evt/status/fmt/json");
 
float tempC = 0.0;
float humidity = 0.0;
 
dht DHT;
YunClient wifiClient;
PubSubClient client(servername, 1883, 0, wifiClient);
 
void setup()
{
 
   // Start the Yun Bridge
   Bridge.begin();
   Serial.begin(9600);
   
}
 
void loop()
{ 
   
  char clientStr[34];
  clientName.toCharArray(clientStr,34);
  char topicStr[26];
  topicName.toCharArray(topicStr,26);
   
  // Read the Temperature and humuditiy data from the DHT sensor
  getData();
 
  if (!client.connected()) {
    Serial.print("Trying to connect to: ");
    Serial.println(clientStr);
    
    Serial.println("Connecting to server "); 
    while (! client.connect(clientStr))
    {
      Serial.println("Re-Connecting to server");
      delay(3000);
    }
   Serial.println("Connected to server");
     
  }
   
  if (client.connected() ) {
     
    Serial.println("Connected to server : Building jason");
     
    String json = buildJson();
    char jsonStr[200];
    json.toCharArray(jsonStr,200);
    Serial.println("Connected to server : publishing");
    boolean pubresult = client.publish(topicStr,jsonStr);
    Serial.print("attempt to send ");
    Serial.println(jsonStr);
    Serial.print("to ");
    Serial.println(topicStr);
    if (pubresult)
     Serial.println("successfully sent");
    else
      Serial.println("unsuccessfully sent");
  }
  else  Serial.println("not Yet connected");
   
  delay(5000);
}
 
String buildJson() {
  String data = "{";
  data+="\n";
  data+= "\"d\": {";
  data+="\n";
  data+="\"Device\": \"LinkIt Smart 7688 Duo DHT\",";
  data+="\n";
  data+="\"temperature (C)\": ";
  data+=(int)tempC;
  data+= ",";
  data+="\n";
  data+="\"humidity\": ";
  data+=(int)humidity;
  data+="\n";
  data+="}";
  data+="\n";
  data+="}";
  return data;
}
 
void getData() {
 
   int chk = DHT.read22(DHT22_PIN);
   if(chk == DHTLIB_OK)
    {
        Serial.println("------------------------------");
 
        tempC = DHT.temperature; 
        humidity = DHT.humidity;
       
         
        Serial.print("temperature = ");
        Serial.println(tempC);
        Serial.print("humidity = ");
        Serial.println(humidity);
    }
    else
    {
         Serial.print("Sensor Error: Temperature Read FAILED !!");
         // Setting the temperature and humidity values to ZERO. !!
         tempC = 0.0; 
         humidity = 0.0;
    }
     
}

Run your application

Follow the instructions in the get started with the LinkIt Smart 7688 Duo development board to upload and run the sketch.

To observe the real-time data on the IBM Watson IoT platform:

  1. Open a browser and navigate to the quick start page of the IBM Watson IoT platform.
  2. Enter your device’s MAC address defined in Define the variables, then click Go.
    Connecting to your LinkIt 7688 Duo from IBM BluemixObserve the real-time sensor data output:

The real-time sensor data output