• Home
  • Archive
  • Tools
  • Contact Us

The Customize Windows

Technology Journal

  • Cloud Computing
  • Computer
  • Digital Photography
  • Windows 7
  • Archive
  • Cloud Computing
  • Virtualization
  • Computer and Internet
  • Digital Photography
  • Android
  • Sysadmin
  • Electronics
  • Big Data
  • Virtualization
  • Downloads
  • Web Development
  • Apple
  • Android
Advertisement
You are here:Home » WROOM ESP32 Example Codes For IBM Watson IoT Platform

By Abhishek Ghosh February 22, 2019 9:34 pm Updated on February 23, 2019

WROOM ESP32 Example Codes For IBM Watson IoT Platform

Advertisement

Here are few WROOM ESP32 example codes for IBM Watson IoT Platform so that anyone can get started with both of them the need of having huge experience. To follow this guide, one should have followed this guide on WROOM ESP32 dev boards to setup on Windows 10 PC. Next, one should read this kind of guide to open free account on IBM Cloud and create a new device ready to get connected with WROOM ESP32 dev board.

On IBM Watson IoT dashboard, you’ll get the Security option. Change the settings to TLS/HTTPS optional to make two of our sketches working. This is a mandatory step to avoid seeing failing authorization on the log. After you get used with a secure handshake, you probably will use strict TLS/HTTPS. Do not forget you did this change on security settings.

 

ESP32 Example Codes For IBM Cloud IoT Platform

 

There is no need of external hardware more than WROOM ESP32 dev board. Our one example has LED blink of on board LED. The effect and the board under question shown below :

Advertisement

---

WROOM ESP32 Example Codes For IBM Watson IoT Platform

We kept the codes on GitHub as repository. We will suggest using the code from there from the RAW file. We are providing some textual explanation here with code. A code may get wrongly copied chars from here.

For two of the codes, you need to install “PubSubClient” library from Arduino IDE’s manage library option. There are many detailed guides on the web about how to add library within Arduino IDE.

On Arduino’s serial monitor, you’ll see the output and also watch IBM Watson IoT’s particular device’s log. This sketches and testing for understanding whether the thing works. Later, you can create an application on IBM Cloud, connect it and do advanced graphing (we will not show that part on this guide).

Our first sketch simple-connect.ino starts with these, you’ll require to change ssid, password, ORG, DEVICE_TYPE, DEVICE_ID, TOKEN :

Vim
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
 
const char* ssid = "your hotspot";
const char* password = "abcdefgh";
 
#define ORG "abishek678"
#define DEVICE_TYPE "yourtype"
#define DEVICE_ID "your id"
#define TOKEN "your token"
 
...

Here is the complete code :

simple-connect.ino
Vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
 
const char* ssid = "your hotspot";
const char* password = "abcdefgh";
 
#define ORG "abishek678"
#define DEVICE_TYPE "yourtype"
#define DEVICE_ID "your id"
#define TOKEN "your token"
 
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char pubTopic[] = "iot-2/evt/status/fmt/json";
char subTopic[] = "iot-2/cmd/test/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
 
WiFiClient wifiClient;
PubSubClient client(server, 1883, NULL, wifiClient);
 
void setup() {
Serial.begin(115200); delay(1); Serial.println();
 
initWiFi();
}
 
void loop() {
 
if (!!!client.connected()) {
   Serial.print("Reconnecting client to "); Serial.println(server);
   while (!!!client.connect(clientId, authMethod, token)) {
     Serial.print(".");
     delay(500);
   }
   Serial.println();
}
 
String payload = "{ \"d\" : {\"counter\":";
payload += millis()/1000;
payload += "}}";
Serial.print("Sending payload: "); Serial.println(payload);
if (client.publish(pubTopic, (char*) payload.c_str())) {
   Serial.println("Publish ok");
} else {
   Serial.println("Publish failed");
}
 
delay(3000);
}
 
void initWiFi() {
Serial.print("Connecting to "); Serial.print(ssid);
if (strcmp (WiFi.SSID().c_str(), ssid) != 0) {
   WiFi.begin(ssid, password);
}
while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
}
Serial.println(""); Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP());
}

Our second sketch simple-https.ino starts with these, you’ll require to change ssid, password, ORG, DEVICE_TYPE, DEVICE_ID, TOKEN :

Vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <base64.h>
 
#define USE_SERIAL Serial
 
const char* ssid = "your hotspot";
const char* password = "abcdefgh";
 
#define ORG "abishek678"
#define DEVICE_TYPE "yourtype"
#define DEVICE_ID "your id"
#define TOKEN "your token"
#define EVENT "myEvent"
 
...

Here is the complete code :

simple-https.ino
Vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <base64.h>
 
#define USE_SERIAL Serial
 
const char* ssid = "your hotspot";
const char* password = "abcdefgh";
 
#define ORG "abishek678"
#define DEVICE_TYPE "yourtype"
#define DEVICE_ID "your id"
#define TOKEN "your token"
#define EVENT "myEvent"
 
String urlPath = "/api/v0002/device/types/" DEVICE_TYPE "/devices/" DEVICE_ID "/events/" EVENT;
String urlHost = ORG ".messaging.internetofthings.ibmcloud.com";
int urlPort = 8883;
String authHeader;
 
void setup() {
  Serial.begin(115200); Serial.println();
  initWifi();
  Serial.println("View the published data on Watson at: ");
  if (ORG == "quickstart") {
    Serial.println("https://quickstart.internetofthings.ibmcloud.com/#/device/" DEVICE_ID "/sensor/");
  } else {
    Serial.println("https://" ORG ".internetofthings.ibmcloud.com/dashboard/#/devices/browse/drilldown/" DEVICE_TYPE "/" DEVICE_ID);
  }  
  if (ORG == "quickstart") {
    authHeader = "";
  } else {
    authHeader = "Authorization: Basic " + base64::encode("use-token-auth:" TOKEN) + "\r\n";
  }  
}
 
void loop() {
  doWiFiClientSecure();
  delay(10000);
}
 
void doWiFiClientSecure() {
WiFiClientSecure client;
Serial.print("connect: "); Serial.println(urlHost);
while ( ! client.connect(urlHost.c_str(), urlPort)) {
    Serial.print(".");
}
Serial.println("Connected");
String postData = String("{  \"d\": {\"aMessage\": \"") + millis()/1000 + "\"}  }";
String msg = "POST " + urlPath + " HTTP/1.1\r\n"
                "Host: " + urlHost + "\r\n"
                "" + authHeader + ""
                "Content-Type: application/json\r\n"
                "Content-Length: " + postData.length() + "\r\n"
                "\r\n" + postData;
                
client.print(msg);
Serial.print(msg);
 
Serial.print("\n*** Request sent, receiving response...");
while (!!!client.available()) {
    delay(50);
Serial.print(".");
  }
  
Serial.println();
Serial.println("Got response");  
  while(client.available()){
  Serial.write(client.read());
  }
Serial.println(); Serial.println("closing connection");
  client.stop();
}
 
void initWifi() {
  Serial.print("Connecting to: "); Serial.print(WiFi.SSID());
  WiFi.mode(WIFI_STA);  
  WiFi.begin(ssid, password);  
  while (WiFi.status() != WL_CONNECTED) {
     delay(250);
     Serial.print(".");
  }
  
  Serial.println("");
  Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP());
 
}

Our third sketch temperature.ino starts with these, you’ll require to change ssid, password, ORG, DEVICE_TYPE, DEVICE_ID, TOKEN :

Vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
 
// <------- CHANGE PARAMETERS BELOW THIS LINE ------------>
 
const char ledPin = 2;
 
const char* ssid = "YOUR-HOTSPOT-NAME";
const char* password = "YOUR-HOTSPOT-PASSWORD";
 
#define ORG "YOUR-ORG-NAME-ON-IBM-DASHBOARD"
#define DEVICE_TYPE "YOUR-SET-DEVICE-TYPE"
#define DEVICE_ID "YOUR-SET-DEVICE-ID"
#define TOKEN "YOUR-SET-TOKEN-OR-AUTOGENERATED-TOKEN"
 
// <------- CHANGE PARAMETERS ABOVE THIS LINE ------------>
 
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char pubTopic[] = "iot-2/evt/status/fmt/json";
char subTopic[] = "iot-2/cmd/test/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
 
 
...

Here is the complete code :

temperature.ino
Vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
 
// <------- CHANGE PARAMETERS BELOW THIS LINE ------------>
 
const char ledPin = 2;
 
const char* ssid = "YOUR-HOTSPOT-NAME";
const char* password = "YOUR-HOTSPOT-PASSWORD";
 
#define ORG "YOUR-ORG-NAME-ON-IBM-DASHBOARD"
#define DEVICE_TYPE "YOUR-SET-DEVICE-TYPE"
#define DEVICE_ID "YOUR-SET-DEVICE-ID"
#define TOKEN "YOUR-SET-TOKEN-OR-AUTOGENERATED-TOKEN"
 
// <------- CHANGE PARAMETERS ABOVE THIS LINE ------------>
 
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char pubTopic[] = "iot-2/evt/status/fmt/json";
char subTopic[] = "iot-2/cmd/test/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
 
WiFiClient wifiClient;
PubSubClient client(server, 1883, NULL, wifiClient);
 
void receivedCallback(char* pubTopic, byte* payload, unsigned int length) {
  Serial.print("Message received: ");
  Serial.println(pubTopic);
 
  Serial.print("payload: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  /* we got '1' -> on */
}
 
void setup() {
    Serial.begin(115200);
    Serial.println();
    pinMode(ledPin, OUTPUT);
    Serial.print("Connecting to ");
    Serial.print(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    
    Serial.print("WiFi connected, IP address: ");
    Serial.println(WiFi.localIP());
 
    if (!client.connected()) {
        Serial.print("Reconnecting client to ");
        Serial.println(server);
        while (!client.connect(clientId, authMethod, token)) {
            Serial.print(".");
            delay(500);
        }
        client.setCallback(receivedCallback);
        if (client.subscribe(subTopic)) {
            Serial.println("subscribe to cmd OK");
        } else {
            Serial.println("subscribe to cmd FAILED");
        }
        Serial.println("IBM Watson IoT connected");
    }
}
 
long lastMsg = 0;
long temperature = 0;
 
void loop() {
    client.loop();
    long now = millis();
    if (now - lastMsg > 3000) {
        lastMsg = now;
        temperature = random(0, 40);
        String payload = "{\"d\":{\"Name\":\"" DEVICE_ID "\"";
              payload += ",\"temperature\":";
              payload += temperature;
              payload += "}}";
        Serial.print("Sending payload: ");
        Serial.println(payload);
 
        if (client.publish(pubTopic, (char*) payload.c_str())) {
            Serial.println("Publish ok");
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
        delay(1000);
        } else {
            Serial.println("Publish failed");
        }
    }
}

 

Conclusion

 

Enough coding provided to get started. Next steps are creating own application on IBM cloud for data analysis (or some other work) :

Vim
1
2
3
https://console.bluemix.net/docs/services/IoT/GA_information_management/ga_im_device_twin.html#device_twins
https://www.ibm.com/support/knowledgecenter/SSQP8H/iot/overview/overview.html
https://www.ibm.com/support/knowledgecenter/SSQP8H/iot/developing/develop.html#real-time-analytics

Tagged With esp32 iot platforms , best iot platform for esp32 , define string esp32

This Article Has Been Shared 575 Times!

Facebook Twitter Pinterest

Abhishek Ghosh

About Abhishek Ghosh

Abhishek Ghosh is a Businessman, Surgeon, Author and Blogger. You can keep touch with him on Twitter - @AbhishekCTRL.

Here’s what we’ve got for you which might like :

Articles Related to WROOM ESP32 Example Codes For IBM Watson IoT Platform

  • How to Control Multiple Relays With Single Arduino ESP32?

    Before How to Control Multiple Relays With Single Arduino ESP32 Testing, You Need to Learn How to Create Multiple MQTT Channels & Fetch Data.

  • Connecting ESP32 Arduino with DHT11 with IBM Watson IoT

    Earlier, we described how to create graph on IBM Watson IoT dashboard by using the default widgets. In previous guide, we described how to use ESP32 Arduino with DHT11 sensor. Here is the Code and Diagram to Connect ESP32 Arduino with DHT11 with IBM Watson IoT and Get Odometer Like Gauges on Dashboard. For this […]

  • Detect Smartwatch With ESP32 on IBM Watson IoT Widget

    In our previous guide, we have shown that we can trigger ESP32 (with Arduino IDE) to send message to IBM Watson IoT in Presence of a Particular Samsung Galaxy Smartwatch. That process involves BLE and WiFi. In our one series of articles on Samsung Smartwatch as Proximity Switch, we triggered a local event, such as […]

  • How to Connect Arduino to IBM Cloud (To Send Sensor Data)

    This gives the capabillity of sending data from anywhere like from a car at zero cost. Here is How to Connect Arduino to IBM Cloud (IoT Platform).

performing a search on this website can help you. Also, we have YouTube Videos.

Take The Conversation Further ...

We'd love to know your thoughts on this article.
Meet the Author over on Twitter to join the conversation right now!

If you want to Advertise on our Article or want a Sponsored Article, you are invited to Contact us.

Contact Us

Subscribe To Our Free Newsletter

Get new posts by email:

Please Confirm the Subscription When Approval Email Will Arrive in Your Email Inbox as Second Step.

Search this website…

 

Popular Articles

Our Homepage is best place to find popular articles!

Here Are Some Good to Read Articles :

  • Cloud Computing Service Models
  • What is Cloud Computing?
  • Cloud Computing and Social Networks in Mobile Space
  • ARM Processor Architecture
  • What Camera Mode to Choose
  • Indispensable MySQL queries for custom fields in WordPress
  • Windows 7 Speech Recognition Scripting Related Tutorials

Social Networks

  • Pinterest (24.3K Followers)
  • Twitter (5.8k Followers)
  • Facebook (5.7k Followers)
  • LinkedIn (3.7k Followers)
  • YouTube (1.3k Followers)
  • GitHub (Repository)
  • GitHub (Gists)
Looking to publish sponsored article on our website?

Contact us
Page Visits Alerts

Recent Posts

  • How Can I Take Better Pictures With My Samsung Galaxy S23 Ultra?May 30, 2023
  • What is Document Object Model (DOM)May 30, 2023
  • Configure WordPress to Send Emails Using mSMTPMay 29, 2023
  • Easily Set Up Email with SMTP on Ubuntu ServerMay 29, 2023
  • How to Install and Configure mod_evasive on Ubuntu for WordPressMay 28, 2023

About This Article

Cite this article as: Abhishek Ghosh, "WROOM ESP32 Example Codes For IBM Watson IoT Platform," in The Customize Windows, February 22, 2019, May 31, 2023, https://thecustomizewindows.com/2019/02/wroom-esp32-example-code-ibm-iot/.

Source:The Customize Windows, JiMA.in

PC users can consult Corrine Chorney for Security.

Want to know more about us? Read Notability and Mentions & Our Setup.

Copyright © 2023 - The Customize Windows | dESIGNed by The Customize Windows

Copyright  · Privacy Policy  · Advertising Policy  · Terms of Service  · Refund Policy

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT