|
// Consider hardware debouncing the buttons with a cap |
|
|
|
const long debounceDelay = 50; // the debounce time; increase if there is chatter on the buttons |
|
int buttons[] = {D1, D2, D3}; // Add your button pins here |
|
int outputs[] = {D7, D8}; // Add your button pins here |
|
|
|
// State variables |
|
int outputState[] = {LOW, LOW}; // current state of the output pins |
|
int buttonState[3]; // current reading from the buttons |
|
int previousButtonState[] = {HIGH, HIGH, HIGH}; // previous reading from the buttons |
|
long lastDebounceTime[] = {0, 0, 0}; |
|
|
|
|
|
void setup() { |
|
Serial.begin(57600); |
|
|
|
// set input pin modes |
|
for (int pin = 0; pin < 3; pin++) { |
|
pinMode(buttons[pin], INPUT_PULLUP); |
|
} |
|
|
|
// set output pin modes and initial states |
|
for (int out = 0; out < 2; out++) { |
|
pinMode(outputs[out], OUTPUT); |
|
digitalWrite(outputs[out], outputState[out]); |
|
} |
|
} |
|
|
|
void loop() { |
|
// check if any buttons were pushed |
|
if (checkButtons()) { |
|
|
|
for (int pin = 0; pin < 3; pin++) { |
|
Serial.print("Button "); |
|
Serial.print(pin); |
|
Serial.print(" : "); |
|
Serial.println(buttonState[pin]); |
|
} |
|
|
|
// button 1 pressed |
|
if (buttonState[0] == LOW) { |
|
// invert state |
|
outputState[0] = !outputState[0]; |
|
} |
|
|
|
// button 2 pressed |
|
if (buttonState[1] == LOW) { |
|
// invert state |
|
outputState[1] = !outputState[1]; |
|
} |
|
|
|
// button 3 pressed |
|
if (buttonState[2] == LOW) { |
|
// invert both states |
|
outputState[0] = !outputState[0]; |
|
outputState[1] = !outputState[1]; |
|
} |
|
|
|
// set output states |
|
for (int pin = 0; pin < 2; pin++) { |
|
digitalWrite(outputs[pin], outputState[pin]); |
|
} |
|
} |
|
} |
|
|
|
bool checkButtons() { |
|
|
|
bool buttonPressed = false; |
|
|
|
// loop through buttons |
|
for (int pin = 0; pin < 3; pin++) { |
|
int reading = digitalRead(buttons[pin]); |
|
|
|
// reset the debouncing timer if the state has changed |
|
if (reading != previousButtonState[pin]) { |
|
lastDebounceTime[pin] = millis(); |
|
} |
|
|
|
// if the debounce delay is met check if there is a change |
|
if ((millis() - lastDebounceTime[pin]) > debounceDelay) { |
|
// if the button state has changed: |
|
if (reading != buttonState[pin]) { |
|
buttonState[pin] = reading; |
|
|
|
// save flag for button pressed |
|
if (buttonState[pin] == LOW) { |
|
buttonPressed = true; |
|
} |
|
} |
|
} |
|
|
|
// save current state as previous for next loop |
|
previousButtonState[pin] = reading; |
|
} |
|
|
|
return buttonPressed; |
|
} |