This section of my project isn't working as intended.
The code is meant to have 2 LED's light separately depending on the state of a button (LED1 HIGH on button push and LED2 HIGH on button lift) and when the button is held down for 2+ seconds the LEDs will change places, or "reverse" their positions.
However, the transition isn't smooth. I'd have hoped that LED1 is HIGH when the button is pushed, mode change is made on the release of the button, then remains HIGH as it now represents the button not being pushed. Somehow LED2 blinks once quicky during this transition.
const int button1 = 2;
const int led1 = 8;
const int led2 = 9;
int buttonStatePrevious = HIGH;
unsigned long minButtonLongPressDuration = 2000;
unsigned long buttonLongPressMillis;
bool buttonStateLongPress = false;
const int intervalButton = 50;
unsigned long previousButtonMillis;
unsigned long buttonPressDuration;
unsigned long currentMillis;
bool reverse = false;
void setup() {
pinMode(button1, INPUT_PULLUP);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
}
void readButtonState() {
if(currentMillis - previousButtonMillis > intervalButton) {
int buttonState = digitalRead(button1);
//PRESSED
if (buttonState == LOW && buttonStatePrevious == HIGH && !buttonStateLongPress) {
buttonLongPressMillis = currentMillis;
buttonStatePrevious = LOW;}
buttonPressDuration = currentMillis - buttonLongPressMillis;
//LONG PRESS
if (buttonState == LOW && !buttonStateLongPress && buttonPressDuration >= minButtonLongPressDuration) {
buttonStateLongPress = true;}
//RELEASED
if (buttonState == HIGH && buttonStatePrevious == LOW && buttonStateLongPress == false) {
buttonStatePrevious = HIGH;
buttonStateLongPress = false;}
//RELEASED LONG
if (buttonState == HIGH && buttonStatePrevious == LOW && buttonStateLongPress == true) {
buttonStatePrevious = HIGH;
buttonStateLongPress = false;
reverse = !reverse;}
previousButtonMillis = currentMillis;}
}
void loop() {
currentMillis = millis();
readButtonState();
int buttonState = digitalRead(button1);
if (reverse == false){
if (buttonState == LOW){
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);}
if (buttonState == HIGH){
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);}
}
if (reverse == true){
if (buttonState == LOW){
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);}
if (buttonState == HIGH){
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);}
}
}