Blinking Lights while a switch is on and no lights when a switch is off

I am struggling to get an ESP32 to make an LED blink continuously until the switch is disengaged. It will either have a counter and continue blinking until the counter is finished even if the switch is disengaged or it will delay a certain amount of times and then stop before the switch is disengaged. Is there a way to get the LED to blink continuously until the user turns it off with the switch?

Thanks for the help!

Some view of your code might help, as would a view of how you have your LED and switch connected.

Bit hard to help in the dark.

Study blink without delay (built in example in the IDE) and just add the reading of your switch as an extra condition to get the blinking

case 3:  
        while(Serial.print("Left Blinker:"); Serial.println(value)){;
        digitalWrite(left_blinker, HIGH);   // turn the left blinker on (HIGH is the voltage level)
        delay(300);                       // wait for 300 micro-seconds
        digitalWrite(left_blinker, LOW);    // turn the left blinker off by making the voltage LOW
        delay(300); }                      // wait for 300 micro-seconds 
        break;

You don’t want to use delay, it’s blocking and you won’t read your switch during that time

For extra information and examples look at Using millis() for timing. A beginners guide and Several things at the same time

Hi there

Please have look at this code. You only have to change the pins which you want to use in your project. Most importantly, read and understand about millis().

unsigned long startMillis;  //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 500;  //the value is a number of milliseconds
const byte ledPin = 13;    //using the built in LED

void setup()
{
  Serial.begin(115200);  //start Serial in case we need to print debugging info
  pinMode(ledPin, OUTPUT);
  pinMode(7, INPUT_PULLUP);

  startMillis = millis();  //initial start time
}

void loop()
{
  currentMillis = millis();  //get the current "time" (actually the number of milliseconds since the program started)

  if (!digitalRead(7)) {
    if (currentMillis - startMillis >= period)  //test whether the period has elapsed
    {
      digitalWrite(ledPin, !digitalRead(ledPin));  //if so, change the state of the LED.  Uses a neat trick to change the state
      startMillis = currentMillis;  //IMPORTANT to save the start time of the current LED state.
    }
  }
  else {
    digitalWrite(ledPin, LOW);  //if so, change the state of the LED.  Uses a neat trick to change the state

  }

}

Please feel free to reply for any help

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.