We Can Use millis()
To Perform Many Things Without Using the delay()
Function. We can code to read a push button to determine the rate at which the LED should blink. In that system, if we hold the push button down for x milliseconds, the LED will blink on and off every x milliseconds. Here is Arduino Blink LED Rate Depending On Push Button Press Duration Guide With Circuit and Code. For our regular readers, just for recall with Arduino and basic coding, we already have some similar guides like :
- LED Blink Rate Control With LDR
- Blink LED and Beep Every X Seconds Upon Push Button Press
- Flip-Flop Blinking LED With Push Button
- Blink LED With Pushbutton Control to Turn ON and Off
In most of those guides, our basis is this example guide on millis()
:
1 | https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay |
More newer users can check official guide on just control of one LED with push button :
---
1 | https://www.arduino.cc/en/Tutorial/Button |
Code And Connection To Blink LED Rate Depending On Push Button Press Duration
We can connect LED to Pin 13 of Arduino and push button to Pin 6 of Arduino and run this code :
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 | int ledPin = 13; int ledValue = LOW; long ledStartTime = 0; long ledBlinkInterval = 1000; int buttonPin = 6; int buttonValue = HIGH; long buttonPressTime = 0; void setup() { pinMode(ledPin, OUTPUT); } void loop() { buttonValue = digitalRead(buttonPin); if (buttonValue==LOW && buttonPressTime==0) { buttonPressTime = millis(); } if (buttonValue==HIGH && buttonPressTime!=0) { ledBlinkInterval = millis() - buttonPressTime; buttonPressTime = 0; } if (millis() - ledStartTime > ledBlinkInterval) { ledStartTime = millis(); if (ledValue == LOW) ledValue = HIGH; else ledValue = LOW; digitalWrite(ledPin, ledValue); } } |
What the code is doing? First, we are telling that the LED is connected to digital pin 13, LOW
is the previous value of the LED. ledStartTime
will store last time LED was updated. ledBlinkInterval
is the interval at which to blink. Then we have set a momentary pushbutton on pin 6, stating HIGH
is the current state of the button. In void setup()
, we have set the LED pin as output.
In void loop(), from the line
buttonValue = digitalRead(buttonPin);` we are checking if the button is pressed and mark the time upon press and when is released. From that calculate how long it was pressed. Then carry the value to make the led to blink at the same rate.