I'll help you modify the code to include multiple switches and relays as you specified. Here's the updated Arduino code
Let me explain the key changes:
1. I've used arrays to manage multiple switches and relays:
- `switchPins[]` stores the input switch pins (2-7)
- `relayPins[]` stores the corresponding relay output pins (8-13)
- `numSwitches` defines the total number of switches/relays
2. In `setup()`:
- Configures each switch pin as INPUT_PULLUP
- Configures each relay pin as OUTPUT
- Initializes all relays to OFF (LOW state)
3. In `loop()`:
- Iterates through all switches
- Checks each switch for a press
- Toggles the corresponding relay on/off when pressed
- Includes a small delay to debounce the switch
The code works exactly like the original, but now supports 6 switches and relays simultaneously. Each switch controls its corresponding relay, toggling on/off with each press.
const int switchPins[] = {2, 3, 4, 5, 6, 7}; // Switch pins
const int relayPins[] = {8, 9, 10, 11, 12, 13}; // Corresponding relay pins
const int numSwitches = 6; // Number of switches/relays
// Arrays to store switch and relay states
bool switchStates[6] = {false};
bool relayStates[6] = {false};
void setup() {
// Configure switch pins with internal pull-up resistors
for (int i = 0; i < numSwitches; i++) {
pinMode(switchPins[i], INPUT_PULLUP);
pinMode(relayPins[i], OUTPUT);
// Initialize relays to OFF (LOW)
digitalWrite(relayPins[i], LOW);
}
}
void loop() {
// Check each switch
for (int i = 0; i < numSwitches; i++) {
// Read the current state of the switch
int reading = digitalRead(switchPins[i]);
// Check if switch is pressed (LOW indicates switch is pressed)
if (reading == LOW) {
// Toggle relay state
relayStates[i] = !relayStates[i];
// Update relay pin
digitalWrite(relayPins[i], relayStates[i] ? HIGH : LOW);
// Delay to prevent multiple triggers from a single press
delay(250);
}
}
}