/*
https://forum.arduino.cc/t/how-to-control-the-off-time-of-led-using-timer-interrupt/1177480/7
2023-10-12 by noiasca
sketch
*/
const uint8_t ledPin = 13; // Define the pin where your solenoid valve is connected
const uint8_t buttonAPin = 10; // Define the pin for Push Button A
const uint8_t buttonBPin = 11;
const uint8_t buttonStopPin = 12;
uint8_t ledState = LOW; // Track if the valve is currently open
uint32_t startTime = 0; // Record the start time of the cycle
uint32_t previousMillis = 0; // track millis for blink sequence
// A B
const uint32_t openTime[] = {500, 1000}; // in milliseconds
const uint32_t closeTime[] = {1000, 2000}; // in milliseconds
const uint32_t runTime[] = {6000, 12000};
enum Mode {A, B, IDLE} mode = IDLE; // 3 defined modes, in this case IDLE needs to be the last mode
// run the finite state machine to handle the LED
void runFSM() {
if (mode == IDLE) return; // nothing to do - return early
uint32_t currentMillis = millis(); // Record the current time
if (ledState == HIGH && currentMillis - previousMillis > openTime[mode]) {
//Serial.println(F("switch to LOW"));
previousMillis = currentMillis;
ledState = LOW;
digitalWrite(ledPin, ledState);
}
else if (ledState == LOW && currentMillis - previousMillis > closeTime[mode]) {
//Serial.println(F("switch to HIGH"));
previousMillis = currentMillis;
ledState = HIGH;
digitalWrite(ledPin, ledState);
}
else if (currentMillis - startTime > runTime[mode]) {
Serial.println(F("runtime end"));
mode = IDLE;
ledState = LOW;
digitalWrite(ledPin, ledState);
}
}
void readButton() {
if (mode == IDLE && digitalRead(buttonAPin) == LOW) {
Serial.println(F("Button A is pressed"));
mode = A;
startTime = millis(); // Record the start time
previousMillis = millis();
ledState = HIGH;
digitalWrite(ledPin, ledState);
}
if (mode == IDLE && digitalRead(buttonBPin) == LOW) {
Serial.println(F("Button B is pressed"));
mode = B;
startTime = millis(); // Record the start time
previousMillis = millis();
ledState = HIGH;
digitalWrite(ledPin, ledState);
}
if (digitalRead(buttonStopPin) == LOW) {
Serial.println(F("Button Stop is pressed"));
mode = IDLE;
ledState = LOW;
digitalWrite(ledPin, ledState);
}
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(buttonAPin, INPUT_PULLUP);
pinMode(buttonBPin, INPUT_PULLUP);
pinMode(buttonStopPin, INPUT_PULLUP);
}
void loop() {
readButton();
runFSM();
}
//