• 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 Blink LED With Pushbutton Control to Turn ON and Off

By Abhishek Ghosh July 18, 2018 2:43 pm Updated on July 18, 2018

Arduino Blink LED With Pushbutton Control to Turn ON and Off

Advertisement

We already know that we can blink one LED with Arduino and also we can blink one LED with 555 IC. We can also blink 2 LEDs alternatively with Arduino and also blink 2 LEDs alternatively with 555 IC. From our older examples, we can start LED to be on with one pushbutton press and turn-off with another pushbutton keypress. Arduino Blink LED With Pushbutton Control to Turn ON and Off is Few Steps Higher Than Basic Example. There is Matter of Repeat Checking by Microcontroller. It is not exactly easy to a beginner but mandatory next step to learn.

 

Arduino Blink LED With Pushbutton Control to Turn ON and Off

 

Wiring/circuit diagram of this project is very easy. One digital pin of Arduino will be connected to LED, LED’s another leg will be connected to GND of Arduino. Alternatively, the onboard LED on Arduino board can be used. Connection for pushbutton is easy too – one digital pin of Arduino will be connected to pushbutton, pushbutton’s another leg will be connected to GND of Arduino with a resistor with value like 1K Ohm to ensure not much current going back to Arduino board.

Arduino Blink LED With Pushbutton Control to Turn ON and Off

Very basic code will be :

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
const int kPinBtn = 2;
const int kPinLed = 13;
 
boolean kPress = false;
 
void setup()
{
  pinMode(kPinBtn, INPUT_PULLUP);
  pinMode(kPinLed, OUTPUT);
}
 
void loop()
{
  if(digitalRead(kPinBtn) == LOW && kPress == false)
  {
    digitalWrite(kPinLed, HIGH);
    kPress = true;
  }
  if(digitalRead(kPinBtn) == LOW && kPress == true)
  {
    digitalWrite(kPinLed, LOW);
    kPress = false;
  }  
}

You will notice the odd with a delay. If we want to achieve is to have a button alternate between blink and off smoothly, that can be done in this way:

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
enum { LED=13, ButtonPin=2, BounceMS=50, BlinkMS=256 };
unsigned long buttonAt;
bool blinky, bouncy, buttonState;
 
void setup() {
  pinMode(LED, OUTPUT);
  pinMode(ButtonPin, INPUT_PULLUP);
  blinky = bouncy = buttonState = false;
  buttonAt = millis();
}
 
void loop() {
  // Detect button changes
  if (bouncy) {
    if (millis() - buttonAt > BounceMS)
      bouncy = false;       // End of debounce period
  } else {
    if (digitalRead(ButtonPin) != buttonState) {
      buttonState = digitalRead(ButtonPin);
      buttonAt = millis();
      bouncy = true;        // Start debounce period
      if (buttonState) {    // Was button just pressed?
        blinky = !blinky;   // Toggle blink-state
      }
    }
  }
  // Control light-blinking
  if (blinky) {
    // Turn LED on for BlinkMS ms, then off for same
    digitalWrite(LED, (millis() - buttonAt)%(2*BlinkMS) < BlinkMS);
  } else {
    digitalWrite(LED, LOW);
  }
}

We can not directly use easy logic to start and stop. That will leads to a very long time between successive checks of the button as there is a delay between cycles! That invites some other functions to use, like using the millis function. Notice some changes in connection in this diagram :

Arduino Blink LED With Pushbutton Control

Another code with millis :

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
/* Pushbutton-controlled blinking LED
* David A. Mellis
* http://arduino.berlios.de
*/
int ledPin = 13;                // LED connected to digital pin 13
int ledValue = LOW;             // previous value of the LED
long ledStartTime = 0;          // will store last time LED was updated
long ledBlinkInterval = 1000;   // interval at which to blink (milliseconds)
 
int buttonPin = 2;              // an active-high momentary pushbutton on pin 2
int buttonValue = HIGH;         // the current state of the button
long buttonPressTime = 0;       // will store the time that the button was pressed
 
 
void setup()
{
pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}
 
void loop()
{
// Check to see if the button is pressed.  If so, mark the time.  When the
// button is released, calculate how long it was pressed, and make the led
// blink at the same rate.
buttonValue = digitalRead(buttonPin);
 
// button press
if (buttonValue==LOW && buttonPressTime==0) {
   buttonPressTime = millis();  // capture the time of the press
}
 
// button release
if (buttonValue==HIGH && buttonPressTime!=0) {
   ledBlinkInterval = millis() - buttonPressTime;  // set the new flash interval
   buttonPressTime = 0;                            // clear the button press time
}
 
// check to see if it's time to blink the LED; that is, is the difference
// between the current time and last time we blinked the LED bigger than
// the interval at which we want to blink the LED.
if (millis() - ledStartTime > ledBlinkInterval) {
   ledStartTime = millis();   // remember the last time we blinked the LED
 
   // if the LED is off turn it on and vice-versa.
   if (ledValue == LOW)
     ledValue = HIGH;
   else
     ledValue = LOW;
 
   digitalWrite(ledPin, ledValue);
}
}

We can use timer library :

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
#include "Timer.h"
 
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
const int led = 13;
const int buttonPin = 2;
 
// declare state variables as global
bool buttonState = LOW;
bool buttonState_prev = LOW;
bool toggleBlinking;
bool blinkState;
 
// declare a Timer object so blinking can be done without loosing button presses
Timer timer_b;
int blink_id;
 
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
 
  // initial state: toggle led each 1000 ms
  blink_id = timer_b.oscillate(led, 1000, HIGH);
  blinkState = true;
  toggleBlinking = false;
}
 
// the loop routine runs over and over again forever:
void loop() {
  // Update the timer (required)
  timer_b.update();
 
  // check if button has been pressed (HIGH to LOW),
  // then debounce it and raise toggle flag
  buttonState = digitalRead(buttonPin);
  if ((buttonState != buttonState_prev) && (buttonState_prev == HIGH)) {
    // simple button debounce (confirm press after some ms)
    delay (50);
    buttonState = digitalRead(buttonPin);
    if (buttonState != buttonState_prev) toggleBlinking = true;
  }
 
  // keep current LED state unless the button has been pushed
  switch (blinkState) {
    case true:
      // if button has been pushed, stop blinking and change LED state
      if (toggleBlinking == true) {
        timer_b.stop (blink_id);
        blinkState = false;
      }
      break;
    case false:
      digitalWrite(led, LOW);
      // if button has been pushed, start blinking and change LED state
      if (toggleBlinking == true) {
        blink_id = timer_b.oscillate(led, 1000, HIGH);
        blinkState = true;
      }
      break;
  }
 
  buttonState_prev = buttonState;
  toggleBlinking = false;
}

This ends this tutorial.

Tagged With arduino led on off button code , arduino blink , arduino led blink with button , arduino led blink , arduino blink with button , arduino keypress , arduino blinking led , arduino control led with pushbutton , светодиод управляемый кнопкой arduino , arduino pushbutton led

This Article Has Been Shared 431 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 Blink LED With Pushbutton Control to Turn ON and Off

  • Arduino Temperature Humidity Sensor : New DHT11, DHT21, DHT22 Test Code

    Here is New Test Codes For Arduino Temperature Humidity Sensor DHT11, DHT21, DHT22 Test Code as Hardware (Not Shields). 2 Libraries Needed.

  • Arduino TFT Touch Screen Calculator (MCUFRIEND) : Part 1

    Arduino TFT Touch Screen Calculator is an Easy Example of Practical Deployment of Programmable Microcontroller From the Libraries.

  • DIY Electronic Component Storage Cabinet : For Arduino Hobbyists

    After Initial Days, Many Arduino Hobbyists Find Difficulty in Storing the Modules, Electronic Components, Tools. Here is an Article on DIY Electronic Component Storage Cabinet.

  • Regular IR Distance Sensor Vs Sharp IR Distance Sensor (Arduino, Pi)

    Normally For Arduino We use Regular IR Distance Sensor Modules. Normally For Arduino We use Regular IR Distance Sensor Modules. Regular IR Distance Sensor Vs Sharp IR Distance Sensor Comparison Has Reasons For Features.

  • What is I²C Protocol? Relevance of I²C in Arduino

    Previously, we discussed about UART. What is I²C Protocol? I squared C (also pronounced as I-two-C) or I²C is a bus serial communication protocol designed by Philips for home automation and home electronics applications. Since 2006, licensing fees not needed to implement the I²C protocol. Fees needed to obtain I²C slave addresses allocated by NXP. […]

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 is Configuration Management February 5, 2023
  • What is ChatGPT? February 3, 2023
  • Zebronics Pixaplay 16 : Entry Level Movie Projector Review February 2, 2023
  • What is Voice User Interface (VUI) January 31, 2023
  • Proxy Server: Design Pattern in Programming January 30, 2023

About This Article

Cite this article as: Abhishek Ghosh, "Arduino Blink LED With Pushbutton Control to Turn ON and Off," in The Customize Windows, July 18, 2018, February 6, 2023, https://thecustomizewindows.com/2018/07/arduino-blink-led-with-pushbutton-control-to-turn-on-and-off/.

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