/*
Forum: https://forum.arduino.cc/t/einfache-if-schleife/1176612
Wokwi: https://wokwi.com/projects/378131879225047041
*/
#include <Servo.h>
int servoPin = 9;
const int button_pin = 13;
Servo servo;
int closed = 90; // servo position in degrees
int open = 0;
int oldState = 1;
int state = 1;
int button;
void setup()
{
Serial.begin(9600);
servo.attach(servoPin);
pinMode(button_pin, INPUT_PULLUP);
servo.write(open);
}
void loop()
{
if (buttonJustDown()) {
state = !state;
}
if (state != oldState){
oldState = state;
switch (state){
case 0: servo.write(closed);
break;
case 1: servo.write(open);
break;
}
}
}
boolean buttonJustDown(){
static unsigned long lastChange = 0;
static byte buttonState = HIGH;
static byte lastState = HIGH;
boolean justDown = false;
byte actState = digitalRead(button_pin);
if (actState != lastState) {
lastChange = millis();
lastState = actState;
}
if (actState != buttonState && millis()-lastChange > 30){
buttonState = actState;
if (buttonState == LOW) {
justDown = true;
}
}
return justDown;
}