// https://forum.arduino.cc/t/button-timing-and-loops/1223168
// https://wokwi.com/projects/390016797849980929
unsigned long my3SecondTimer = 0; // Timer-variables MUST be of type unsigned long
unsigned long my350mSecsTimer = 0; // Timer-variables MUST be of type unsigned long
const byte buttonPin = 17;
const byte heaterPin = 39;
byte buttonState;
boolean heatingStarted = false;
const byte released = HIGH;
const byte pressed = LOW;
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start");
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite (heaterPin, LOW);
pinMode(heaterPin, OUTPUT);
Serial.println("press button to start heater-cycle");
}
void loop() {
// if heating has not yet started read in the button
if (heatingStarted == false) {
buttonState = digitalRead(buttonPin);
if ( buttonState == pressed ) {
Serial.println("Start-Button pressed start heater cycle heater-pulsing");
heatingStarted = true; // indicate heating HAS started
my3SecondTimer = millis(); // store actual time
my350mSecsTimer = millis(); // store actual time
digitalWrite(heaterPin,HIGH);
}
}
else { // heating HAS started and is running
// check if 350 milliseconds have pased by since heating started
if ( TimePeriodIsOver(my350mSecsTimer, 350) ) {
// when 350 milliseconds REALLY HAVE passed by
// update timervariable with name "my350mSecsTimer" automatically
// for next interval
invertHeaterStateOnOff(); // say what it does
}
// check if 3000 milliseconds have passed by since heating started
if ( TimePeriodIsOver(my3SecondTimer, 3000) ) {
// when 3000 milliseconds REALLY HAVE passed by
// not reevant here: update timervariable with name "my3SecondTimer" automatically
Serial.println("3 seconds over heater switched OFF");
digitalWrite(heaterPin, LOW);
Serial.println("heating cycle finished press button for new heater-cycle");
Serial.println();
heatingStarted = false;
}
}
}
void invertHeaterStateOnOff() {
if ( digitalRead(heaterPin) == HIGH) {
digitalWrite(heaterPin, LOW);
Serial.println("Heater switched OFF");
}
else {
digitalWrite(heaterPin, HIGH);
Serial.println("Heater switched ON");
}
}
// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - startOfPeriod >= TimePeriod ) {
// more time than TimePeriod has elapsed since last time if-condition was true
startOfPeriod = currentMillis; // a new period starts right here so set new starttime
return true;
}
else return false; // actual TimePeriod is NOT yet over
}