• 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 » ESP32 Deep Sleep : Push Button Message to IBM Watson IoT

By Abhishek Ghosh May 28, 2019 11:36 pm Updated on May 28, 2019

ESP32 Deep Sleep : Push Button Message to IBM Watson IoT

Advertisement

We already demonstrated how to send message to IBM Watson IoT platform using ESP32 Arduino with just a button press. We have several non-IoT guides on pushbutton with Arduino including simple basic Arduino Blink LED With Pushbutton. Learning various logics with pushbutton will hugely help the beginners as pushbutton from the binary way of thought is a basic sensor to convey 0 or 1. Working with the sensors factually need minor modification from pushbutton projects. Those who are unused with IBM Watson IoT can read our getting started guide. Watson IoT is free tier is enough for this kind of projects. You will need to disable TLS/SSL security from IBM Watson IoT dashboard. Snippets for IBM Watson IoT is easy to convert to generic MQTT IoT projects. Many of the software parts IBM uses is Open Source.

It is better to go through our ESP32 Deep Sleep Guide and test the basic examples. To repeat the same basic theory: power saving is an important factor for the IoT applications and by saving power we can make one IoT project running with two AA batteries over a year. Deep Sleep turns off CPUs and most of the RAM and peripherals which are clocked from `APB_CLK`. The RTC controller, RTC peripherals and RTC memories are parts of the chip which can keep powered on. So, we must remember that both Wi-Fi and Bluetooth are powered off. However, the chip will store Wi-Fi and Bluetooth connection data in the RTC memory (`RTC_DATA_ATTR` attribute). If we want to store it into the RTC memory then we will define a global variable like `RTC_DATA_ATTR intboot count = 0;`.

This time, our code is an example of initiating Deep Sleep and waking up using a single push button. We talked about ESP32 wake-up external wake-up. We have two types of triggers – `ext0` when we want to wake-up the chip by one particular pin only and `ext1` –when we have several pins for the wake-up. Our example is with `ext0`.

Advertisement

---

We already have a dedicated repository for IBM Watson IoT for ESP32. This article’s code is also inside that repository.

There is no complex connection, circuit diagram for this project. Only adding a pushbutton to Pin 33 will work for this guide :

ESP32 Deep Sleep Push Button Message to IBM Watson IoT

Next part is the code. We must inform you that our this coding is not fully “scientific”! We made the coding part easier yet fool proof by some cheating on our older code.

// this example uses one push button attached to pin 33
// push button attached to pin 33 sends message and puts it in to deep sleep
// again pushing the pushbutton attached to pin 33 it wakes up from sleep
// LED function kept as the this originated from my non deep-sleep code, it is not made working by code 

// written by Dr. Abhishek Ghosh, https://thecustomizewindows.com
// released under GNU GPL 3.0
// 

#define BUTTON_PIN_BITMASK 0x200000000 // 2^33 in hex; pin 33 for push button
RTC_DATA_ATTR int bootCount = 0;

const byte BUTTON=33; // boot button pin (built-in on ESP32)
const byte LED=2; // onboard LED (built-in on ESP32)

#include 
#include 
#include 
#include 
#define USE_SERIAL Serial 

#define FORCE_MODE 3
 
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 = "fill up";
const char* password = "fill up";

#define ORG "write here" // change
#define DEVICE_TYPE "change" // change
#define DEVICE_ID "change" // change
#define TOKEN "copy-paste" // change
#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 deep_sleep() {
    printf("Sleep at %d ms\n\n", millis());
    delay(20);
    // esp_sleep_enable_timer_wakeup(20000 * 1000); // Deep-Sleep time in microseconds
    esp_sleep_enable_ext0_wakeup(GPIO_NUM_33,1); //1 = High, 0 = Low 
    esp_deep_sleep_start();
    // Serial.println("This will never be printed");

}
 
void setup() {
 Serial.begin(115200); Serial.println();
 delay(1000); //Take some time to open up the Serial Monitor
 //Increment boot number and print it every reboot
  ++bootCount;
Serial.println("Boot number: " + String(bootCount));
 pinMode(BUTTON, INPUT_PULLUP);
 pinMode(LED, OUTPUT);
 digitalWrite(LED, LOW);

initWifi();
authHeader = "Authorization: Basic " + base64::encode("use-token-auth:" TOKEN) + "\r\n";
doWiFiClientSecure();
loop();
}

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());

}

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); 
   }
 }
deep_sleep();               
}

We have tested the above thing and it is working except the LED blink part (it is not fixed yet). Basically within `void setup() {`, we are calling the other functions. From coding point of view, the way we achieved is dirty. We did it for faster achieving the result using our old code to send message to IBM Watson IoT. Deep Sleep is stopping the `void loop()` :

...

void setup() {
…

initWifi();
authHeader = "Authorization: Basic " + base64::encode("use-token-auth:" TOKEN) + "\r\n";
doWiFiClientSecure();
loop();
}
...

It does the job but the logical steps are better to be construct in clean way. If you are student, you should re-write it in clean manner for your engineering project.

Tagged With push button led in esp32 , deep sleep , esp32 push button to sleep , Schéma simple switch bouton esp32

This Article Has Been Shared 567 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 ESP32 Deep Sleep : Push Button Message to IBM Watson IoT

  • ESP32 Arduino : Create a Webpage to Control a Relay Module

    Here is How to Create a Webpage to Control a Relay Module Using ESP32 Arduino. This is a basic example which provides the base of advanced projects.

  • Arduino ESP32 : Turn on LED on Button Press and Turn Off After a Period

    Here is How to Turn on LED on Button Press and Turn Off After a Period on Arduino ESP32. For this guide, we will use onboard boot button and onboard LED.

  • ESP32 Arduino with DHT11 Sensor : Connection & Code

    Here is Connection & Working Code for ESP32 Arduino with DHT11 Sensor. We will use Adafruit’s libraries for DHT11 and DH22 Temperature Humidity Modules.

  • ESP32 Arduino Built-in Hall Sensor Code & Theory

    ESP32 has a Hall Effect Sensor near pin 22. Here is ESP32 Arduino Built-in Hall Sensor Code & Theory. Here is something about Hall Effect Sensor as well.

  • ESP32 Arduino OLED Display Example (I2C)

    Interfacing OLED without I2C is difficult with ESP32, as it requires 6 connections. I2C based OLED display need only two IO lines.

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

  • Exploring the Benefits and Advantages of Microsoft’s Operating System March 22, 2023
  • Web Design Cookbook: Accessibility March 21, 2023
  • Online Dating: How to Find Your Match March 20, 2023
  • Web Design Cookbook: Logo March 19, 2023
  • How Starlink Internet Works March 17, 2023

About This Article

Cite this article as: Abhishek Ghosh, "ESP32 Deep Sleep : Push Button Message to IBM Watson IoT," in The Customize Windows, May 28, 2019, March 22, 2023, https://thecustomizewindows.com/2019/05/esp32-deep-sleep-push-button-message-to-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