• 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 458 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 (22.1K 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

  • Samsung Galaxy S22 Ultra: Long Term Review June 30, 2022
  • How to Make the Most of Your S Pen (S22 Ultra) June 29, 2022
  • Safe Chargers for Samsung Galaxy S22 Ultra June 27, 2022
  • How Telecoms Can Use The Cloud To Power Their 5G Network June 24, 2022
  • A Beginner Guide to Cloud Computing for Development June 22, 2022

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, July 1, 2022, https://thecustomizewindows.com/2019/05/esp32-deep-sleep-push-button-message-to-ibm-watson-iot/.

Source:The Customize Windows, JiMA.in

This website uses cookies. If you do not want to allow us to use cookies and/or non-personalized Ads, kindly clear browser cookies after closing this webpage.

Read Privacy Policy.

PC users can consult Corrine Chorney for Security.

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

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

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