• 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 : Turn on LED on Button Press and Turn Off After a Period

By Abhishek Ghosh March 10, 2019 1:53 am Updated on March 10, 2019

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

Advertisement

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 the onboard boot button and the onboard LED of ESP32. You can not use the EN button of ESP32 for this purpose. The onboard boot button is attached to Pin 0 and the onboard LED of ESP32 attached to Pin 2.

This guide has more usage on advanced projects of IoT. Instead of LED, the job can be sending an alert or turning on bulb over the internet. The code of this guide is dependent on millis(), avoiding delay(). If you are new, you should read the function references on Arduino’s official site.

First, in slightly easy way :

Advertisement

---

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
void setup()
{
  pinMode(2,OUTPUT); // LED output
  pinMode(0,INPUT); // Button input
}
 
void loop()
{
  static unsigned char ledState = LOW;
  static unsigned char buttonState = LOW;
  static unsigned char lastButtonState = LOW;
  static unsigned long ledCameOn = 0;
  
  // If the LED has been on for at least 5 seconds then turn it off.
  if(ledState == HIGH)
  {
    if(millis()-ledCameOn > 5000)
    {
      digitalWrite(2,LOW);
      ledState = LOW;
    }
  }
 
  // If the button's state has changed, then turn the LED on IF it is not on already.
  buttonState = digitalRead(0);
  if(buttonState != lastButtonState)
  {
    lastButtonState = buttonState;
    if((buttonState == HIGH) && (ledState == LOW))
    {
      digitalWrite(2,HIGH);
      ledState = HIGH;
      ledCameOn = millis();
    }
  }
}

Now some programming matters. Using const instead of define may not consume RAM. unsigned long stores the the current value of millis() when the event takes place.

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

This is the final code with more control on timing of when LED will be on :

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
const byte BUTTON=0; // boot button pin (built-in on ESP32)
const byte LED=2; // onboard LED (built-in on ESP32)
unsigned long buttonPushedMillis; // when button was released
unsigned long ledTurnedOnAt; // when led was turned on
unsigned long turnOnDelay = 20; // wait to turn on LED, 20 almost instant
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.
void setup() {
pinMode(BUTTON, INPUT_PULLUP);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
}
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);
     // 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);
   }
}
}

The above code was originally written by James of baldengineer.com. It is near perfect and avoids various physical problems with buttons.

Tagged With arduino esp32 , esp32 button , esp32 boot button , esp32 arduino read button , button press duration arduino , arduino esp32 turn on led on button , esp32 2019 , arduino button press screen on off , arduino 8 relay board rf and millis , esp32 arduino read buttons

This Article Has Been Shared 321 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 : Turn on LED on Button Press and Turn Off After a Period

  • ESP32 Deep Sleep : Push Button Message to IBM Watson IoT

    ESP32 Deep Sleep With Push Button Message to IBM Watson IoT is an Basic Project Which Will Help Like Template to Create More Complex Projects.

  • Simple Level Shifter With Transistors (3.3V-5V)

    Earlier, we talked about the level shifter. Raspberry Pi, ESP32 etc things operate at 3.3v logic whereas, relay modules usually need near 5v TTL logic level. In our guide to control AC appliances over the internet with ESP32, you will notice that directly connecting the relay with ESP32 will not properly work – it will […]

  • Connect ESP32 Arduino With a Samsung Smart Watch

    We can create an ESP32 Web Server, connect & control LED from watch browser. Here is How to Connect ESP32 Arduino With Samsung Smart Watch.

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

  • Pikocube : ESP8285 MCU Powered PCB LED Cube With Gyroscope

    Pikocube is a funny, geeky LED cube dice project with 54 LEDs, gyroscope and Wi-Fi-control made by maker Moekoe from Germany. The dice consists of an ESP8285-01F MCU, six PCBs, a 150mAh lithium battery and charging circuit, an ADXL345 gyroscope, and 54 LEDs. Its structural design is quite clever. Of course, the project is open […]

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

  • 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
  • Advantages of Cloud Server Over Dedicated Server for Hosting WordPress March 26, 2023

About This Article

Cite this article as: Abhishek Ghosh, "Arduino ESP32 : Turn on LED on Button Press and Turn Off After a Period," in The Customize Windows, March 10, 2019, March 31, 2023, https://thecustomizewindows.com/2019/03/arduino-esp32-turn-on-led-on-button-press-and-turn-off-after-a-period/.

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