Trying to control this LED with those 2 pushbuttons - one button that starts a short flashing sequence, another pushbutton acts like a toggle switch, one press bulb is on, another press bulb is off.

If I switch the LED on and then push the flashing button, the on-off flashing starts but then the LED is shut off because off is the last state of the flashing sequence. How do I make the led turn to original state?

#include <ezButton.h>

const int flashing_pin = 2; 
const int switch_pin = 3;
const int led_pin = 8; 

ezButton button(switch_pin);

int ledState = LOW; 

void setup() {
  pinMode(led_pin, OUTPUT); 

void loop() {

  if(button.isPressed()) {

    ledState = !ledState;

    digitalWrite(led_pin, ledState); 
  if( digitalRead(flashing_pin) == LOW )   {

void doFlash(uint8_t number_of_times)  {
  while(  number_of_times-- > 0 ) {

To explain what I want in short;

  • if LED is off - flashing sequence works like "ON OFF ON OFF"
  • if LED is on - flashing sequence works like "OFF ON OFF ON"

enter image description here

  • digitalWrite(led_pin,HIGH); is hardwired ... digitalWrite(led_pin,!ledstate); is opposite to current state
    – jsotola
    Mar 17 at 1:01
  • I got it to work! But I'm confused by the loop state, in my original code there's a rule to doFlash(4); and delay 250 - but when using !ledstate, the 4 flashes are no longer 4 time (ON-OFF) cycles, it's half of it, and the 250 delay is double the time, it's half a second....so in order to get the desired "frequency" 4 flashes in 2 seconds, I need to put doFlash 8 and delay 125....can't figure out why :D but it works
    – Varonne
    Mar 17 at 9:00
  • My flash part of the code is this now; void doFlash(uint8_t number_of_times) { while( number_of_times-- > 0 ) { ledState = !ledState; digitalWrite(led_pin, ledState); delay(125); digitalWrite(led_pin, ledState); delay(125); }
    – Varonne
    Mar 17 at 17:09
  • i guess is that you have not looked at what you wrote very closely
    – jsotola
    Mar 17 at 18:23
  • ledState = !ledState does not belong in the blink code
    – jsotola
    Mar 17 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.