• 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
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

  • WROOM ESP32 Example Codes For IBM Watson IoT Platform

    Here Are Few WROOM ESP32 Example Codes For IBM Watson IoT Platform So That Anyone Can Get Started With Both of Them Without Huge Experience.

  • 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 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.

  • IoT Based Pulse Oximeter With ESP32, MAX30102 and IBM Watson IoT

    Pulse oximeters are in use since long during an operation, in intensive care, in the emergency room and other places such as in unpressurized aircraft. The COVID-19 pandemic made pulse oximetry technology for the consumers. Most of the finger pulse oximeters in the market lack BLE and Wi-Fi. There are only a few finger pulse […]

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

  • PowerAmp Settings for Higher Sound QualityOctober 4, 2023
  • Affordable Earphone/IEM for Audiophiles: HiFiMan RE-400 WaterlineOctober 2, 2023
  • What is Hardware Security Module (HSM)September 30, 2023
  • Transducer Technologies of HeadphonesSeptember 28, 2023
  • What is Analog-to-Digital Converter (ADC)September 27, 2023
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