/*
Forum: https://forum.arduino.cc/t/uno-and-momentary-switches/1400949
Wokwi: https://wokwi.com/projects/438715198606145537
Modified sketch to control six bi-colour leds (each simulated in Wokwi by two leds and a resistor)
Each slide switch occupies only one digital pin that is kept HIGH by INPUT_PULLUP while the switch is open
and goes to LOW when the switch closes to GND.
As Wokwi does not provide MCP23X17 ICs a MEGA is used and the 16 pins of each MCP is mapped to
either pins 22 to 37 or to pins 38 to 53. The library FAKE_MCP23X17.h emulates those functions of
Adafruit_MCP23X17.h which are relevant for this application.
2025/08/08
ec2021
*/
#include "FAKE_MCP23X17.h"
constexpr uint8_t numLeds {6};
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);
}
// Show that all leds can be set to green
setAllToGreen();
delay(2000);
// Show that all leds can be set to red
setAllToRed();
delay(2000);
// Turn all leds off
turnOffLeds();
delay(2000);
// 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() {
checkSwitches();
}
void checkSwitches() {
for (int i = 0; i < numLeds; i++) {
byte state = mcp2.digitalRead(i);
if (state != slideState[i]) {
slideState[i] = state;
if (state) {
setLedGreen(i);
} else {
setLedRed(i);
}
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 turnOffLeds() {
for (int i = 0; i < numLeds; i++) {
uint8_t pin = ( i * 2);
mcp1.digitalWrite(pin, LOW);
mcp1.digitalWrite(pin + 1, LOW);
}
}
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);
}