I had a problem with sticking the buttons, here is an attempt to solve the problem
const int relayPin = 7;
const int buttonPin = 2;
bool buttonpress = false;
bool stateswitch = false;
int buttonState = 0;
int lastButtonState = 0;
unsigned long buttonOnTime;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(relayPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if ((buttonState == HIGH) && (millis() - buttonOnTime > 500)) {
buttonOnTime = millis();
if (stateswitch)
{
Serial.println("Button off");
}
else
{
Serial.println("Button on");
}
stateswitch = !stateswitch;
// delay(500);
} else if ((buttonState == HIGH))
{
buttonOnTime = millis();
}
//
// buttonState = digitalRead(buttonPin);
// if ((buttonState == HIGH)) {
//
// Serial.print("Button:");
// Serial.println(buttonState);
// Serial.print("Relay:");
// stateswitch = digitalRead(relayPin);
// Serial.println(stateswitch);
// digitalWrite(relayPin, !stateswitch);
//
//
// }
// delay(200);
//
// if (buttonState == HIGH) {
// //Serial.println("HIGH");
// digitalWrite(relayPin, HIGH);
// }
// else
// {
// //Serial.println("LOW");
// digitalWrite(relayPin, LOW);
// }
// put your main code here, to run repeatedly:
// digitalWrite(relayPin, LOW);
// delay(5000);
// digitalWrite(relayPin, HIGH);
// delay(5000);
}