// Define the pins connected to the relays
const int relayPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // Pins for 8-channel relays
void setup() {
// Initialize serial communication at 9600 baud
Serial.begin(9600);
// Set relay pins as outputs
for (int i = 0; i < 8; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], 0); // Turn off all relays initially
}
}
void loop() {
if (Serial.available() > 0) { // Check if data is available to read
char receivedChar = Serial.read(); // Read the incoming byte
// Use switch-case to control relays based on the received character
switch (receivedChar) {
case '1':
controlRelay(0, 1); // Turn on relay 1
break;
case '2':
controlRelay(0, 0); // Turn off relay 1
break;
case '3':
controlRelay(1, 1); // Turn on relay 2
break;
case '4':
controlRelay(1, 0); // Turn off relay 2
break;
case '5':
controlRelay(2, 1); // Turn on relay 3
break;
case '6':
controlRelay(2, 0); // Turn off relay 3
break;
case '7':
controlRelay(3, 1); // Turn on relay 4
break;
case '8':
controlRelay(3, 0); // Turn off relay 4
break;
case '9':
controlRelay(4, 1); // Turn on relay 5
break;
case 'A':
controlRelay(4, 0); // Turn off relay 5
break;
case 'B':
controlRelay(5, 1); // Turn on relay 6
break;
case 'C':
controlRelay(5, 0); // Turn off relay 6
break;
case 'D':
controlRelay(6, 1); // Turn on relay 7
break;
case 'E':
controlRelay(6, 0); // Turn off relay 7
break;
case 'F':
controlRelay(7, 1); // Turn on relay 8
break;
case 'G':
controlRelay(7, 0); // Turn off relay 8
break;
case 'H':
for (int i = 0; i < 8; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], 1); // Turn on all relays initially
delay(100);
}
break;
case 'I':
for (int i = 0; i < 8; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], 0); // Turn off all relays initially
delay(100);
}
break;
default:
Serial.println(" ");
}
}
}
// Function to control a relay
void controlRelay(int relayIndex, int state) {
if (relayIndex >= 0 && relayIndex < 8) {
digitalWrite(relayPins[relayIndex], state);
if (state == LOW) {
Serial.print("Relay ");
Serial.print(relayIndex + 1);
Serial.println(" is turned ON.");
} else {
Serial.print("Relay ");
Serial.print(relayIndex + 1);
Serial.println(" is turned OFF.");
}
} else {
Serial.println("Invalid relay index.");
}
}