// Switch on several LEDs by one Switch
// https://forum.arduino.cc/t/16-input-12v-latching-buttons-to-16-12v-leds/1145473
// 2023-07-07 by noiasca
// code to be added to forum
// make outputs human readable ...
// don't use GPIO 0 because a) this is used by Serial and b) we will use 0 as magic number for "no output"
const uint8_t out1 = 23; // GPIO for output
const uint8_t out2 = 25;
const uint8_t out3 = 27;
const uint8_t out4 = 29;
const uint8_t out5 = 31;
const uint8_t out6 = 33;
//Inputs
const uint8_t in[] = {A0, A1, A2, A3}; // GPIOs for switches
const size_t noOfIn = sizeof(in); // how many switches are connected
// logic/matrix
const size_t matrixWidth = 6; // any reasonable number for the maximum parallel active outputs
const uint8_t matrix[noOfIn][matrixWidth] = {
{ out2, out4, out6}, // first switch (index = 0) will activate these outputs
{ out1, out3, out5},
{ out2, out3, out6},
{ out1} // unused indices will get 0, hence why you should not use GPIO 0 in that sketch for any thing else than Serial
};
void readInputsAndHandleLEDs() {
// not super nice, but we need to switch of all pins before we read the button state and switch them on individually
digitalWrite(out1, LOW);
digitalWrite(out2, LOW);
digitalWrite(out3, LOW);
digitalWrite(out4, LOW);
digitalWrite(out5, LOW);
digitalWrite(out6, LOW);
// now loop through all switches and activate the LEDs if the switch is closed (LOW)
for (size_t i = 0; i < noOfIn; i++) {
for (size_t j = 0; j < matrixWidth; j++) {
if (digitalRead(in[i]) == LOW && matrix[i][j] > 0) digitalWrite(matrix[i][j], HIGH);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(out1, OUTPUT);
pinMode(out2, OUTPUT);
pinMode(out3, OUTPUT);
pinMode(out4, OUTPUT);
pinMode(out5, OUTPUT);
pinMode(out6, OUTPUT);
for (auto &i : in) pinMode(i, INPUT_PULLUP); // switches are connected to GND, hence we need the internal pullup to get stable readings
}
void loop() {
readInputsAndHandleLEDs();
}