• 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 » Arduino ESP32 : HTTP(S) POST Request to IBM Watson IoT on Button Press

By Abhishek Ghosh March 10, 2019 10:52 am Updated on March 10, 2019

Arduino ESP32 : HTTP(S) POST Request to IBM Watson IoT on Button Press

Advertisement

Here is How to Send an HTTP POST Request to IBM Watson IoT on Button Press from Arduino ESP32. The basic is dependent on our earlier two separate examples, first is the set of working examples of codes for IBM Watson IoT and second is the example of using a button press to make a LED turn on for a pre-defined time. Earlier, we had another example of using Blynk to send a basic push message on a button press. That Bylnk’s example was for satisfying peoples who want a quick fix in an easy way. That way is not methodical, it abstracts the software and hardware too much, also not reliable.

There is nothing new to say about how to setup ESP32 to use with Arduino IDE.

If you want the code, that is readily available on our GitHub repo. We want to say something on HTTP POST of IBM Watson IoT.

Advertisement

---

To securely send an event called myEvent to the platform with organisation id ‘xfd8ls’, device id HTTPDevice and device type HTTPdeviceType we issue this POST request:

Vim
1
https://xfd8ls.messaging.internetofthings.ibmcloud.com:8883/api/v0002/device/types/HTTPdeviceType/devices/HTTPDevice/events/myEvent

From the above example, you have to keep polling the server to see if there was a message waiting. That is fine for some purposes. We can set the body of the message to:

Vim
1
{"waitTimeSecs": 10}

The number represents a number of seconds. This way you can effectively set your code to wait for a command to arrive. This official guide talking about the thing we are doing but in complex way with Raspberry Pi :

Vim
1
https://developer.ibm.com/recipes/tutorials/publish-device-events-to-ibm-iot-foundation-using-https/

And here is more detailed documentation :

Vim
1
https://console.bluemix.net/docs/services/IoT/devices/api.html#api

For our this code, you will get the raw data from the Recent Events tab on IBM Watson IoT Platform and also, the
Logs there will show authentication, connection and disconnection. These facts proves that remote server “understood” your button press. Also on Arduino IDE’s serial console, you will get meaningful output. This is a meaningful illustration :

Arduino ESP32 HTTPS POST Request to IBM Watson IoT on Button Press

Here are more useful docs :

Vim
1
2
https://developer.ibm.com/recipes/tutorials/publish-device-events-to-ibm-iot-foundation-using-https/
https://www.ibm.com/support/knowledgecenter/en/SSQP8H/iot/platform/devices/api.html

And here is the full code :

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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// connects once upon pressing ESP32 boot pushbutton (GPIO 0) button and sends a message, closes connection
// written by Dr. Abhishek Ghosh, https://thecustomizewindows.com
// released under GNU GPL 3.0
 
 
 
const byte BUTTON=0; // boot button pin (built-in on ESP32)
const byte LED=2; // onboard LED (built-in on ESP32)
 
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <base64.h>
#define USE_SERIAL Serial
unsigned long buttonPushedMillis; // when button was released
unsigned long ledTurnedOnAt; // when led was turned on
unsigned long turnOnDelay = 20; // wait to turn on LED
unsigned long turnOffDelay = 5000; // turn off LED after this time
bool ledReady = false; // flag for when button is let go
bool ledState = false; // for LED is on or not.
 
const char* ssid = "your wifi hotspot";
const char* password = "password of the above";
 
#define ORG "your org on ibm"
#define DEVICE_TYPE "name you given"
#define DEVICE_ID "name you given"
#define TOKEN "your token"
#define EVENT "myEvent" // example
 
// <------- CHANGE PARAMETERS ABOVE THIS LINE ------------>
 
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() {
pinMode(BUTTON, INPUT_PULLUP);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
Serial.begin(115200); Serial.println();
initWifi();
authHeader = "Authorization: Basic " + base64::encode("use-token-auth:" TOKEN) + "\r\n";
}
void loop() {
// get the time at the start of this loop()
unsigned long currentMillis = millis();
// check the button
if (digitalRead(BUTTON) == LOW) {
  // update the time when button was pushed
  buttonPushedMillis = currentMillis;
  ledReady = true;
}
  
// make sure this code isn't checked until after button has been let go
if (ledReady) {
   //this is typical millis code here:
   if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) {
     // okay, enough time has passed since the button was let go.
     digitalWrite(LED, HIGH);
     doWiFiClientSecure();
     // setup our next "state"
     ledState = true;
     // save when the LED turned on
     ledTurnedOnAt = currentMillis;
     // wait for next button press
     ledReady = false;
   }
}
  
// see if we are watching for the time to turn off LED
if (ledState) {
   // okay, led on, check for now long
   if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay) {
     ledState = false;
     digitalWrite(LED, LOW);
   }
}
}
 
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());
 
}

Tagged With esp32 http post , iot arduino , ibm watson insertbutton */( button , http request with hw button , http post request arduino esp32 , http post in esp32 arduino , esp32 wificlientsecure https POST AWS , esp32 ir obstacle sensor example , esp32 ibm , unable to send an HTTP request via httpclient to IBM watson

This Article Has Been Shared 409 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 Arduino ESP32 : HTTP(S) POST Request to IBM Watson IoT on Button Press

  • Arduino ESP32 Basic Graphing/Visualization on IBM Watson IoT Platform

    IBM’s IoT platform provides widgets for simple graphing which avoids pushing own application. We can use our example code to get basic temperature graphng.

  • 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 […]

  • Scope of ESP32 in Commercial IoT Products

    Can ESP32 Used in Commercial IoT Products? Yes, ESP32 has modules and SoC to fit your production need. However, Arduino IDE is not for production.

  • Control Multiple AC Appliances With One ESP32 Arduino

    Here is how to use ESP32 and IBM Watson IoT to control multiple relays (i.e. multiple AC appliances) by pushbutton and over the internet.

  • Develop WEB Applications with ESP32 and IBM Watson IoT

    Here is How to Develop WEB Applications with ESP32 and IBM Watson IoT. Often, using a HTML page with JavaScript is practical than developing and Android App.

Additionally, 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

Recent Posts

  • The Importance of Voice and Style in Essay Writing April 1, 2023
  • What Online Casinos Have No Deposit Bonus in Australia March 30, 2023
  • Four Foolproof Tips To Never Run Out Of Blog Ideas For Your Website March 28, 2023
  • The Interactive Entertainment Serving as a Tech Proving Ground March 28, 2023
  • Is it Good to Run Apache Web server and MySQL Database on Separate Cloud Servers? March 27, 2023

About This Article

Cite this article as: Abhishek Ghosh, "Arduino ESP32 : HTTP(S) POST Request to IBM Watson IoT on Button Press," in The Customize Windows, March 10, 2019, April 2, 2023, https://thecustomizewindows.com/2019/03/arduino-esp32-https-post-request-to-ibm-watson-iot-on-button-press/.

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