#include <Servo.h>
Servo servo1;
byte buttonState;
const byte buttonPin = 2;
const byte servoSignalPin = 13;
const byte LED_Pin = 8;
const byte NOT_Active = 0;
unsigned long ServoTimer = 0;
const unsigned long ServoWaitIntervall = 3000;
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start");
pinMode(buttonPin, INPUT);
pinMode(LED_Pin, OUTPUT);
servo1.attach(servoSignalPin);
}
void loop() {
blinkLED(); // blink the LED all the time in parallel to servo waiting in pos 180
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) { // check if button is pressed
if (ServoTimer == NOT_Active) { // if Timer is not yet activated
ServoTimer = millis(); // store snapshot of ACTUAL time into variable "ServoTimer"
Serial.println("buttonState == HIGH");
servo1.write(180);
Serial.println("servo1.write(180) done");
}
}
if (ServoTimer > NOT_Active) { // value greater than zero means Timer IS ACTIVE
if ( TimePeriodIsOver(ServoTimer,ServoWaitIntervall) ) {
ServoTimer = NOT_Active; // DE-activate timer through assigning value zero
servo1.write(0);
Serial.println("servo1.write(0) done");
}
}
}
boolean TimePeriodIsOver (unsigned long &expireTime, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - expireTime >= TimePeriod )
{
expireTime = currentMillis; // set new expireTime
return true; // more time than TimePeriod) has elapsed since last time if-condition was true
}
else return false; // not expired
}
void blinkLED() {
static unsigned long LED_Timer;
static byte LED_State;
LED_State = digitalRead(LED_Pin);
LED_State = !LED_State; // invert the state through the NOT-operator "!"
if ( TimePeriodIsOver(LED_Timer,500) ) {
digitalWrite(LED_Pin, LED_State);
}
}