Need to make a momentary switch act like a toggle switch

The following sketch works well with one exception. The LED only flashes when momentary push button is held down. I need it to flash until I press another button. How do I make this momentary PB (const int pin_lightOn = 43;)act like a toggle switch?

Thanks for the help

const int pin_lightOn = 43;//button to turn on light
const byte lightLed = 36; //light on led
 
bool blinking = false; //defines when blinking should occur
unsigned long blinkInterval = 250; // number of milliseconds for blink
unsigned long currentMillis; // variables to track millis()
unsigned long previousMillis;
 
void setup() {
 pinMode (pin_lightOn, INPUT_PULLUP);
pinMode (lightLed, OUTPUT);
}
 
void loop() {
 // this code blinks the LED
 if (blinking) {
  currentMillis = millis(); // better to store in variable, for less jitter
  if ((unsigned long)(currentMillis - previousMillis) >= blinkInterval) { // enough time passed yet?
   digitalWrite(lightLed, !digitalRead(lightLed)); // shortcut to toggle the LED
   previousMillis = currentMillis; // sets the time we wait "from"
  }
 } else {
  digitalWrite(lightLed, LOW); // force LED off when not blinking
 }
 int reading = digitalRead(pin_lightOn);
 delay(50); // crude de-bouncing
 
 if (reading== LOW) // buttons with pull-up are pressed when LOW
  blinking=true; // start blinking
 else
  blinking=false; // stop blinking
}

Your else is what's stopping it. Your code is saying you want it to start when the button is pressed, and stop when the button is released.

Your blinking boolean is the only thing that should be changed when the button is pressed. Remove your else statement. Have your low state(button pressed) toggle the blinking boolean. Just as you toggled the !digitalRead(lightled)

There is a logical sequence of events that happens in loop(). In your case, the first line is if(blinkking). After that block of code, you determine whether blinking should be true or false.

That just looks ass-backwards to me.

int reading = digitalRead(pin_lightOn);
 delay(50); // crude de-bouncing

No debouncing is done with that code. You'd have to come back and read the pin again after the delay to ensure it is still in the state read in the first reading. Delay of 50 is way too long anyway.

  • Scotty