Hi, I'm controlling a relay, and opto, and an LED with a short press/long press button and I can't seem to figure out why it's not working as I want it to.
Short press toggles the relay and indicator LED as it should, and the long press toggles the opto as it should but long press also turns off the indicator LED. Since the LED is doing exactly what the relay is doing I just can't work out why the LED is turning off but not the relay. What am I doing wrong here?
Eventually I would like the indicator LED to blink a few times to indicate the opto being toggled but first things first...any guidance would be greatly appreciated. I'm doing this with a ATtiny85 by the way.
Code:
#include <ezButton.h>
const int buttonPin = 3; //2
int relayPin = 0;// 5
int optoPin = 1; //6
int ledPin = 2; // 7
const int SHORT_PRESS_TIME = 1000; // 1700 milliseconds
const int LONG_PRESS_TIME = 2500; // 2500 milliseconds
ezButton button(buttonPin); // create ezButton object that attach to pin 7;
int ledState ;
int optoState = LOW;
int relayState = LOW;
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
bool isPressing = false;
bool isLongDetected = false;
void setup() {
pinMode (ledPin, OUTPUT);
pinMode (buttonPin, INPUT_PULLUP);
pinMode (relayPin, OUTPUT);
pinMode (optoPin, OUTPUT);
button.setDebounceTime(30); // set debounce time to 30 milliseconds
digitalWrite (relayPin, relayState);
digitalWrite (optoPin, optoState);
digitalWrite (ledPin, ledState);
}
void loop() {
button.loop(); // MUST call the loop() function first
if (button.isPressed()) {
pressedTime = millis();
isPressing = true;
isLongDetected = false;
}
if (button.isReleased()) {
isPressing = false;
releasedTime = millis();
long pressDuration = releasedTime - pressedTime;
if ( pressDuration < SHORT_PRESS_TIME ) {
relayState = !relayState;
digitalWrite(relayPin, relayState);
ledState = ! ledState;
digitalWrite (ledPin, ledState);
}
}
if (isPressing == true && isLongDetected == false) {
long pressDuration = millis() - pressedTime;
if ( pressDuration > LONG_PRESS_TIME ) {
optoState = ! optoState;
digitalWrite (optoPin, optoState);
isLongDetected = true;
}
}
}