#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// Define LCD properties (16x2)
LiquidCrystal_I2C lcd(0x27, 16, 2); // 0x27 is the I2C address for the LCD
// Define Keypad properties
const byte ROWS = 4; // 4 rows
const byte COLS = 4; // 4 columns
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // Connect to these pins on Arduino
byte colPins[COLS] = {5, 4, 3, 2}; // Connect to these pins on Arduino
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Relay control pins
const int relayPin1 = 10;
const int relayPin2 = 11;
// Variables to store user input
String inputCode = "";
bool selectingRelay = true; // Flag to indicate if selecting first or second relay
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on backlight
// Setup relay pins
pinMode(relayPin1, OUTPUT);
pinMode(relayPin2, OUTPUT);
digitalWrite(relayPin1, LOW); // Initially turn off relay 1
digitalWrite(relayPin2, LOW); // Initially turn off relay 2
// Display initial message on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Pilih status");
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
if (selectingRelay) {
if (key == 'A') { // Enter key for first relay
activateRelay1();
} else if (isDigit(key)) {
inputCode = key;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Pilih status");
lcd.setCursor(0, 1);
lcd.print("Number: ");
lcd.print(inputCode);
}
} else {
if (key == 'A') { // Enter key for second relay
activateRelay2();
}
}
}
}
void activateRelay1() {
int relayNumber = inputCode.toInt();
if (relayNumber == 1) {
digitalWrite(relayPin1, HIGH); // Activate relay 1
selectingRelay = false; // Switch to selecting relay 2
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Pilih status>");
lcd.setCursor(0, 1);
lcd.print("Status Normal");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Invalid selection");
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Press key");
}
}
void activateRelay2() {
int relayNumber = inputCode.toInt();
if (relayNumber == 1) {
digitalWrite(relayPin2, HIGH); // Activate relay 2
digitalWrite(relayPin1, LOW); // Deactivate relay 1
selectingRelay = true; // Switch back to selecting relay 1
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Press key then enter");
lcd.setCursor(0, 1);
lcd.print("Relay 2 active");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Invalid selection");
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Press key then enter");
}
}