/*
Forum: https://forum.arduino.cc/t/uno-and-momentary-switches/1400949
Wokwi: https://wokwi.com/projects/438729902609465345
Emulates a three state slide switch
Off = no button pressed
Up = Green button pressed
Down = Red button pressed
2025/08/08
ec2021
*/
#include "FAKE_MCP23X17.h"
constexpr uint8_t numLeds {2};
constexpr uint8_t board1 {0x20};
constexpr uint8_t board2 {0x21};
Adafruit_MCP23X17 mcp1;
Adafruit_MCP23X17 mcp2;
byte slideState[numLeds];
void setup() {
Serial.begin(115200);
Serial.println("Momentry Switch Test");
// Initialize the MCP23017 using I2C
if (!mcp1.begin_I2C(board2)) {
Serial.println("Error.");
while (1);
}
Serial.println("I2C Board 2 Found...");
if (!mcp2.begin_I2C(board1)) {
Serial.println("Error.");
while (1);
}
Serial.println("I2C Board 1 Found...");
// configure board 1 pins for output
for (int pin = 0; pin <= 15; pin ++) {
mcp1.pinMode(pin, OUTPUT);
}
// configure board 2 pins for input
for (int pin = 0; pin <= 15; pin ++) {
mcp2.pinMode(pin, INPUT_PULLUP);
}
turnOffLeds();
// slideState[] is set to the opposite of the actual state
// to make sure that the first call of checkSwitches()
// will correctly react on the slide switch status
for (int i = 0; i < numLeds; i++) {
slideState[i] = !mcp2.digitalRead(i);
}
}
void loop() {
checkThreeStateSwitches();
}
void checkThreeStateSwitches() {
for (int i = 0; i < numLeds; i++) {
// state 0 when no button pressed or a three state slide switch in middle position
byte state = 0;
// state 1 when green button pressed or a three state slide switch in up position
if (mcp2.digitalRead(i * 2) == LOW) {
state = 1;
};
// state 2 when red button pressed or a three state slide switch in down position
if (mcp2.digitalRead(i * 2 + 1 ) == LOW) {
state = 2;
};
// slideState now holds the states 0, 1 or 2
if (state != slideState[i]) {
slideState[i] = state;
switch (state) {
case 0:
turnOffLed(i);
break;
case 1:
setLedGreen(i);
break;
case 2:
setLedRed(i);
break;
}
}
delay(30); // Very Simple Debouncing
}
}
void setAllToGreen() {
for (int i = 0; i < numLeds; i++) {
setLedGreen(i);
}
}
void setAllToRed() {
for (int i = 0; i < numLeds; i++) {
setLedRed(i);
}
}
void turnOffLed(uint8_t ledNo) {
uint8_t pin = ( ledNo * 2);
mcp1.digitalWrite(pin, LOW);
mcp1.digitalWrite(pin + 1, LOW);
}
void turnOffLeds() {
for (int i = 0; i < numLeds; i++) {
turnOffLed(i);
}
}
void setLedRed(uint8_t ledNo) {
uint8_t pin = (ledNo * 2);
mcp1.digitalWrite(pin, HIGH);
mcp1.digitalWrite(pin + 1, LOW);
}
void setLedGreen(uint8_t ledNo) {
uint8_t pin = (ledNo * 2);
mcp1.digitalWrite(pin, LOW);
mcp1.digitalWrite(pin + 1, HIGH);
}