I am trying to implement a toggle switch to turn blinking ON & OFF. However, the code only turns the led ON or OFF and that too unreliably. Can you help me understand why it isn't working?
const int redLed = 10;
const int buttonPin = 2;
unsigned long newTime;
unsigned long oldTime = 0;
byte newButtonState;
byte oldButtonState = 0;
boolean ledState = false;
boolean blinkState = false;
boolean state = LOW;
void setup() {
pinMode(redLed, OUTPUT);
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop() {
newButtonState = digitalRead(buttonPin);
delay(100);
// check if button state has changed
if (newButtonState != oldButtonState) {
// if button was pushed
if (newButtonState == HIGH) {
// check led state
if (ledState == false) {
ledState = true;
blinkState = true;
} else {
ledState = false;
blinkState = false;
}
if (ledState == true && blinkState == true) {
newTime = millis();
if (newTime - oldTime >= 250) {
state = !state;
oldTime = newTime;
}
digitalWrite(redLed, state);
}
}
}
oldButtonState = newButtonState;
}
if (ledState && blinkState)
, if you want to writeif (ledState == true && blinkState == false)
you can writeif (ledState && !blinkState)