• 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 » Control ESP32 Arduino LED from IBM Watson IoT

By Abhishek Ghosh June 3, 2019 12:38 am Updated on June 3, 2019

Control ESP32 Arduino LED from IBM Watson IoT

Advertisement

Anthony Elder published a guide on developerWorks Recipes on how to “Build your own Watson controlled kettle” for ESP8266. This article’s code is shamelessly ripped-off from him for broader usage. This guide will show how to turn on and turn off a LED connected with ESP32 Arduino from IBM Watson IoT platform. That “remote control” over the internet will be shown by using a simple bash scripts – you can use it from Android Smartphone with Terminal app. You can use a relay with ESP32 instead of LED. Anthony Elder’s work solved the opposite direction of command. Normally, we are used with sending data from ESP32 attached pushbutton or ESP32 attached sensors like DHT11 to IBM Watson IoT. But with this guide, you can control a LED attached with ESP32 from smartphone located anywhere on this earth. If we combine both, then that becomes two-way communication.

Control ESP32 Arduino LED from IBM Watson IoT

I will suggest reading Anthony Elder’s original idea to realize the meaning of the code :

Vim
1
2
3
#
https://developer.ibm.com/recipes/tutorials/build-your-own-watson-controlled-kettle/
#

As he had a physical button too, there is a button code too. It is a great feature as template code. I am going to back-version of his development for a general purpose need. In IBM Watson IoT platform, as usually keep TLS connection as optional. Generate a new API key for your device :

Advertisement

---

Vim
1
2
3
#
https://developer.ibm.com/tutorials/iot-generate-apikey-apitoken/
#

The API key is mentioned as elsewhere in IBM’s documentation.
The Auth token is mentioned as elsewhere in IBM’s documentation.

Copy-paste them in a safe place. You will need both for constructing the cURL command to turn on and off from bash script. Normally, we will need the auth token in the code for ESP32.

The above thing is the difference with the other guides.

 

Required Hardware to Test ESP32 Arduino LED Controlled from IBM Watson IoT

 

For testing propose, only ESP32 will be sufficient. It will be great if you can add three LEDs to Pin 19, Pin 18
and some other pin like Pin 4. We need to check the pin which is defined in DEVICE_RELAY in the code. That is Pin 19 in our code. We suggest to use :

Pin 19 = Yellow LED
Pin 18 = Green LED
Pin 4 = Red LED

Pin 4 and Pin 12 may not work on ESP32! Why that is written here :

Vim
1
2
3
#
https://github.com/espressif/arduino-esp32/issues/1204
#

How funny! The dimension of ESP32 is so odd on a breadboard that I was forced to use the pins of one side. Pin 5 is of the power LED. Pin 2 is onboard LED. During testing the code, I saw that the red LED not glowing ever. As it is not too important for the main goal, I ignored it & pushed the code on GitHub with pin 4. It is a slight China electronics issue. You can use Pin 2 instead of Pin 4.

We have the complete project on GitHub repo. Here is the code for ESP32 Arduino :

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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include <WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>
#include <HTTPClient.h>
#include <SPI.h>
const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPass";
//-------- Customise these values -----------
 
#define ORG "change"
#define DEVICE_TYPE "change"
#define DEVICE_ID "change"
#define TOKEN "change"
 
//-------- Customise the above values --------
 
#define DEVICE_BUTTON 0
#define DEVICE_RELAY 19
#define DEVICE_GREEN_LED 18
#define DEVICE_RED_LED 4
 
Ticker ledBlinker;
 
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
 
#define CMD_STATE "/gpio/"
 
// use the '+' wildcard so it subscribes to any command with any message format
const char commandTopic[] = "iot-2/cmd/+/fmt/+";
 
void gotMsg(char* topic, byte* payload, unsigned int payloadLength);
 
WiFiClient wifiClient;
PubSubClient client(server, 1883, gotMsg, wifiClient);
 
int buttonPressDuration;
 
void setup() {
Serial.begin(115200); Serial.println();
 
pinMode(DEVICE_RELAY, OUTPUT);
pinMode(DEVICE_GREEN_LED, OUTPUT);
pinMode(DEVICE_RED_LED, OUTPUT);
 
ledBlinker.attach(0.1, ledBlink); // fast blink indicates Wifi connecting
wifiConnect();
ledBlinker.attach(0.4, ledBlink); // slower blink indicates MQTT connecting
mqttConnect();
ledBlinker.detach();
digitalWrite(DEVICE_GREEN_LED, LOW); // low is led on to show connected
pinMode(DEVICE_BUTTON, INPUT);
attachInterrupt(DEVICE_BUTTON, buttonPress, CHANGE);
}
 
int lastHeartBeat;
 
void loop() {
if (buttonPressDuration > 0) {
   doCommand(digitalRead(DEVICE_RELAY) ? "off" : "on");
   buttonPressDuration = 0;
}
 
if (!client.loop()) {
   mqttConnect();
}
if (millis()-lastHeartBeat > 10000) {
   Serial.print("loop: gpio "); Serial.print(DEVICE_RELAY); Serial.print(" current state ");
   Serial.println(digitalRead(DEVICE_RELAY) ? "On" : "Off");
   digitalWrite(DEVICE_GREEN_LED, HIGH); // flicker LED to show its active
   delay(200);
   digitalWrite(DEVICE_GREEN_LED, LOW);
   lastHeartBeat = millis();
}
}
 
void gotMsg(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("gotMsg: invoked for topic: "); Serial.println(topic);
if (String(topic).indexOf(CMD_STATE) > 0) {
   String cmd = "";
   for (int i=0; i<payloadLength; i++) {
     cmd += (char)payload[i];
   }
   doCommand(cmd);
} else {
   Serial.print("gotMsg: unexpected topic: "); Serial.println(topic);
}
}
 
void doCommand(String cmd) {
int currentState = digitalRead(DEVICE_RELAY);
int newState = (cmd == "on");
digitalWrite(DEVICE_RELAY, newState);
Serial.print("Relay switched from ");
Serial.print(currentState ? "On" : "Off");Serial.print(" to "); Serial.println(newState ? "On" : "Off");
}
 
unsigned long startPress = 0;
 
void buttonPress() {
int currentState = digitalRead(DEVICE_BUTTON);
if (currentState == 0) { // 0 is pressed, 1 is released
   startPress = millis();
} else {
   int diff = millis() - startPress;
   if (diff > 100) { // debounce
     buttonPressDuration = diff;
   }
}
Serial.print("Button "); Serial.print(currentState ? "released" : "pressed");
Serial.print(" duration="); Serial.println(buttonPressDuration);
}
 
void ledBlink() {
  digitalWrite(DEVICE_GREEN_LED, ! digitalRead(DEVICE_GREEN_LED));
}
 
void wifiConnect() {
Serial.print("Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
}
Serial.print("\nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
 
void mqttConnect() {
if (!!!client.connected()) {
   Serial.print("Reconnecting MQTT client to "); Serial.println(server);
   while (!!!client.connect(clientId, authMethod, token)) {
     Serial.print(".");
     delay(500);
   }
   Serial.println();
}
 
subscribeTo(commandTopic);
}
 
void subscribeTo(const char* topic) {
Serial.print("subscribe to "); Serial.print(topic);
if (client.subscribe(topic)) {
   Serial.println(" OK");
} else {
   Serial.println(" FAILED");
}
}

You can use cURL to test sending the commands:

Vim
1
curl -u <use-the-API-Key>:<use-auth-token> -H "Content-Type: text/plain" -v -X POST http://<your org>.messaging.internetofthings.ibmcloud.com:1883/api/v0002/application/types/<yourDeviceType>/devices/<yourDeviceId>/commands/gpio -d "on"

I have written two easy bash scripts to turn ON :

Vim
1
2
3
4
5
6
7
8
9
#!/bin/bash  
 
CURL='/usr/bin/curl'
 
curl -u <use-the-API-Key>:<use-auth-token> -H "Content-Type: text/plain" -v -X POST http://<your org>.messaging.internetofthings.ibmcloud.com:1883/api/v0002/application/types/<yourDeviceType>/devices/<yourDeviceId>/commands/gpio -d "on"
 
# or you can redirect it into a file:
 
# $CURL  > watson.log

and to turn OFF :

Vim
1
2
3
4
5
6
7
8
9
#!/bin/bash  
 
CURL='/usr/bin/curl'
 
curl -u <use-the-API-Key>:<use-auth-token> -H "Content-Type: text/plain" -v -X POST http://<your org>.messaging.internetofthings.ibmcloud.com:1883/api/v0002/application/types/<yourDeviceType>/devices/<yourDeviceId>/commands/gpio -d "off"
 
# or you can redirect it into a file:
 
# $CURL  > watson.log

Save them with file names such as watson-on-sh and watson-off.sh, CHMOD them :

Vim
1
2
chmod +X watson-on.sh
chmod +X Watson-off.sh

Execute them on need :

Vim
1
2
sh watson-on.sh
sh Watson-off.sh

You can do it from a computer, as well as a terminal app on an Android device. Now, Anthony Elder’s project became “ESP32 and mobile compatible”! Obviously, do it with many kinds of stuff at home you have to develop a real Android application. This ends this guide.

Tagged With Anthony Elder esp32 now , how to turn on led from other computer with esp32 , internet controlled leds using esp32 , watson iot esp32

This Article Has Been Shared 840 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 Control ESP32 Arduino LED from IBM Watson IoT

  • Send Basic Push Message from Arduino ESP32 using Blynk

    How to Send Basic Push Message from Arduino ESP32 using Blynk? With Blynk like web service & library, it is easy to create such basic project.

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

  • ESP32 Arduino IBM Watson IoT Pulse Sensor Amped

    Here is Simple ESP32 Arduino IBM Watson IoT Pulse Monitor With Easy Coding and Default Graphing Widgets of IBM Watson IoT. It is usable for testing purpose.

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

  • ESP32 Arduino and TM1637 Seven Segment LED Display

    TM1637 Seven Segment LED Display is Popular Thing in Arduino Prototyping World. Here is Some Words About Using TM1637 With ESP32 Arduino.

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

  • Get Audiophile-Grade Music on Your Smartphone March 25, 2023
  • Simple Windows Security and Privacy Checklist for 2023 March 24, 2023
  • 7 Best Artificial Intelligence (AI) Software March 24, 2023
  • ESP32 Arduino Water Tank Level Monitoring Using Laser ToF Sensor March 23, 2023
  • Exploring the Benefits and Advantages of Microsoft’s Operating System March 22, 2023

About This Article

Cite this article as: Abhishek Ghosh, "Control ESP32 Arduino LED from IBM Watson IoT," in The Customize Windows, June 3, 2019, March 26, 2023, https://thecustomizewindows.com/2019/06/control-esp32-arduino-led-from-ibm-watson-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