const int relayPin = 7;
const int buttonPin1 = 2;
const int buttonPin2 = 3;
int buttonState1 = 0;
int buttonState2 = 0;
bool switch1Pressed = false;
bool switch2Pressed = false;
void setup() {
pinMode(relayPin, OUTPUT);
pinMode(buttonPin1, INPUT_PULLUP);
pinMode(buttonPin2, INPUT_PULLUP);
}
void loop() {
buttonState1 = digitalRead(buttonPin1);
if (buttonState1 == LOW && !switch1Pressed) {
switch1Pressed = true;
digitalWrite(relayPin, LOW);
}
else if (switch1Pressed) {
digitalWrite(relayPin, LOW);
}
else {
buttonState2 = digitalRead(buttonPin2);
if (buttonState2 == LOW && !switch2Pressed) {
switch2Pressed = true;
digitalWrite(relayPin, HIGH);
}
else if (switch2Pressed) {
digitalWrite(relayPin, HIGH);
}
}
If switch1Pressed equals true, nothing else after the else if will be evaluated. You will have to use two if statements, one for the first switch and one for the second switch.
Hello vel32
It seems to be a school assigment, isn´t it?
Keep in mind the sketch needs the following services:
- an adequate i/o handling
- debouncing of buttons
- state change detection of buttons
- and parts that I´ve forgoten
Take a piece a paper and a pencil and design a program structure before start coding.
Have a nice day and enjoy coding in C++.
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.