Overview

Skill Level: Any Skill Level

Good to have a basic knowledge in any programming language

This recipe is all about sending data from an iot device (sensor, any electronic circuit board,any digital or analog input) to the IBM bluemix platform so that the user can view and use the data when needed.

Ingredients

1. Arduino Uno board.

2. ESP8266 01 wifi serial.

3. Usb cable to connect arduino board with laptop.

4. Arduino IDE in laptop.

5. Jumper wires.

 

 

 

Step-by-step

  1. High level Overview

    1.Connect Arduino uno board with esp8266 01 wifi module.

    2. Login to bluemix account and choose Internet of Things service.

    3. After choosing correct domain create one unique service.

    4.Go to internetofthings.ibmcloud.com and create one device type. Note down the authentication token, device type, device id and organization.

    5. Write program in Arduino ide for board, esp8266 01 initialization and then mqtt connection to publish payload(data) to the iot server.

    6.Upload C/C++ program to Arduino uno via USB cable from laptop.

    7. Open the serial monitor of Arduino ide to watch what is happening.

    8. In serial monitor and internetofthings.ibmcloud.com portal you will be able to see your data and connections.

    Workflow

  2. Bluemix Portal Activities

    1.Login to bluemix.

    1

    2.Click Catalog.

    2

    3.Select IoT and create a service.

    3

    4.Go to Dashboard to see your service is up and running.

    4

     

     

    5

    5.Login to internetofthings.ibmcloud.com.
    Then follow these steps:

    6

     

    6.Generate API key and note down both keys and authentication token.

    7

    8

     

     9

    7.Now at the time of device type creation enter only device name ( must be unique in your org).
    8.Then create a device of that device type with that authentication token generated in previous step.

    10

    9.So our device is ready now to be connected with Arduino, sensors, any iot capable devices.

     

     

  3. Arduino Uno IDE

    1.Download and install Arduino IDE from here : https://www.arduino.cc/en/Main/Software.

    11

    2.Open Arduino and click File>New to open a blank sketch.
    And paste this below code.

    #include <PubSubClient.h>
    //#include<WiFi.h>
    #include <WiFiEspClient.h>
    #include <WiFiEspServer.h>
    #include <WiFiEsp.h>

    #include <WiFiEspUdp.h>
    #include <ArduinoJson.h>

    #include “SoftwareSerial.h”

    #define ORG “***”
    #define DEVICE_TYPE “****”
    #define DEVICE_ID “****”
    #define TOKEN “**************”

    #define WIFI_AP “*******”
    #define WIFI_PASSWORD “*******”
    WiFiEspClient espClient;

    //PubSubClient client(espClient);

    SoftwareSerial soft(2, 3); // RX, TX
    int status = WL_IDLE_STATUS;

    char server[] = ORG “.messaging.internetofthings.ibmcloud.com”;
    char authMethod[] = “use-token-auth”;
    char token[] = TOKEN;
    char clientId[] = “d:” ORG “:” DEVICE_TYPE “:” DEVICE_ID;

    const char publishTopic[] = “iot-2/evt/status/fmt/json”;
    const char responseTopic[] = “iotdm-1/response”;
    const char manageTopic[] = “iotdevice-1/mgmt/manage”;
    const char updateTopic[] = “iotdm-1/device/update”;
    const char rebootTopic[] = “iotdm-1/mgmt/initiate/device/reboot”;

    void callback(char* publishTopic, char* payload, unsigned int payloadLength);

    //WiFiClient wifiClient;
    PubSubClient client(server, 1883, callback, espClient);
    //PubSubClient client(espClient);

    int publishInterval = 30000; // 30 seconds
    long lastPublishMillis;

    void setup() {
    // initialize serial for debugging
    // client.setServer( server, 1883 );
    Serial.begin(115200);
    InitWiFi();
    Serial.print(WiFi.localIP());
    if (!!!client.connected()) {
    Serial.print(“Reconnecting client to “);
    Serial.println(server);
    while (!!!client.connect(clientId, authMethod, token)) {
    Serial.print(“.”);
    //delay(500);
    }
    Serial.println();
    }

    }
    int counter = 0;
    void loop() {

    // if (millis() – lastPublishMillis > publishInterval) {
    String payload = “{\”d\”:”;
    payload += counter++;
    payload += “}”;
    /*const size_t bufferSize = 2*JSON_OBJECT_SIZE(1) + 20;
    DynamicJsonBuffer jsonBuffer(bufferSize);

    const char* payload = “a”;*/

    Serial.print(“Sending payload: “);
    Serial.println(payload);
    // client.publish(publishTopic, payload);
    //if(client.connected())
    //{
    // client.publish(publishTopic, (char *)payload.c_str());
    if (client.publish(publishTopic, (char *)payload.c_str())) {
    Serial.println(“Publish ok”);
    if (!!!client.connected()) {
    Serial.print(“Reconnecting client to “);
    Serial.println(server);
    while (!!!client.connect(clientId, authMethod, token)) {
    Serial.print(“.”);
    //delay(500);
    }
    Serial.println();
    }

    } else {
    Serial.println(“Publish failed”);
    if (!!!client.connected()) {
    Serial.print(“Reconnecting client to “);
    Serial.println(server);
    while (!!!client.connect(clientId, authMethod, token)) {
    Serial.print(“.”);
    //delay(500);
    }
    Serial.println();
    }

    }
    }

    void InitWiFi()
    {
    // initialize serial for ESP module
    soft.begin(115200);
    // initialize ESP module
    WiFi.init(&soft);

    Serial.println(“Connecting to AP …”);
    // attempt to connect to WiFi network
    while ( status != WL_CONNECTED) {
    Serial.print(“Attempting to connect to WPA SSID: “);
    Serial.println(WIFI_AP);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
    delay(500);
    }
    Serial.println(“Connected to AP”);
    }

     

    void callback(char* publishTopic, char* payload, unsigned int length) {
    Serial.println(“callback invoked”);
    }

     

    Change this below “*” with your credentials in the code. WIFI_AP & WIFI_PASSWORD are any available wifi hostspot or router SSID and password.

     

     

    12

     

    13

     

     

  4. Now Upload sketch to Arduino and open the serial monitor in Arduino IDE

    14

     

     

  5. Go to {org}.internetofthings.ibmcloud.com. {org}=your organization id generated in bluemix and open your device.

    15

  6. You can also check logs of connections here:

    16

  7. Further improvements

    To connect the iot data from an android device and also ensuring more robust and efficient (without any packet loss) with esp8266 nodemcu board……………

    17

    18

8 comments on"IBM IoT and Arduino"

  1. SérgioGama July 09, 2018

    Where is Arduino configuration? I just run this recipe and arduino code doesn’t work due to wifi libraries.

    • Soumen Saha July 10, 2018

      To include a library in Arduino you can open the IDE and click to the “Sketch” menu and then Include Library > Manage Libraries.

  2. Hi , I have a IBM IOT output node in node red which send commands to Device connected to arduino..commands are not receiving where as publish is working fine.. I receiving command once in a while like 1 for 1000 attempts.. can u help me , I can share more details over mail

    • This 1/1000 or like that attempts actually happen for esp8266 01 wifi module or any less captive devices. You can try nodemcu module 820.11 g or any other device like that which can work more efficiently with the available wifi hotspots. This is actually bandwidth issue. The device and wifi’s upload download bandwidth have to bit higher and consistent. Otherwise packet loss will happen.

  3. Can this recipe be applied to a coffee maker to make espresso. Or if there is any reference available to create a Iot Platform Coffee machine?

    • Yes sure..automated iot enabled coffee machine can be created via this prototype model. You can just integrate your coffee machine’s control pcb board or i/o plugs with the arduino board and rest of the part may be same.. And also this sonar sensor can act like a coffee mug detector( which will emit coffee just by sensing the mug placement). Best of Luck!

  4. Hi, I am getting an error ‘Data packet send error (1)’ or ‘Data packet send error (2)’ followed by ‘Failed to write to socket 3’ and ‘publish failed’. On the IBM portal connection log, i am able to see that the authentication was successful, but the connection was timed out sometimes and was closed sometimes. There is no data loaded on the web portal. Can you help me fix this?

  5. Thank you for trying. First check in the security tab of the bluemix iot device ( you have created) is having no ssl as the connection method and add your device to whitelist. Then check your hotspot bandwidth. It needs a good bandwidth network connection. Please let me know if you are still having any issue.

Join The Discussion