#include <Wire.h>
#include <Keypad.h>
#include <LiquidCrystal.h>
// #include <LiquidCrystal_I2C.h>
// I2C address of the UNO
#define SLAVE_ADDR 8
// pins for external emergency button
const int EMERGENCY_BTN = 2;
// current floor tracker
int currentFloor = 0;
// keypad setup (4 rows × 3 cols)
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C'},
{ '*', '0', '#', 'D'}
};
byte rowPins[ROWS] = { 23, 25, 27, 29 };
byte colPins[COLS] = { 31, 33, 35, 37 };
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// LCD on pins RS, E, D4, D5, D6, D7
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);
// LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x3F for a 16 chars and 2 line display
void setup() {
Wire.begin(); // join I2C as master
pinMode(EMERGENCY_BTN, INPUT_PULLUP);
lcd.begin(16, 2);
// lcd.init();
// lcd.clear();
// lcd.backlight(); // Make sure backlight is on
// lcd.clear();
lcd.print("Choose floor:");
}
void loop() {
// 1) Check emergency button
if (digitalRead(EMERGENCY_BTN) == LOW) {
sendCommand(0x02, 0); // 0x02 = EMERGENCY
lcd.clear();
lcd.print("EMERGENCY");
delay(2000);
lcd.clear();
lcd.print("Choose floor:");
// debounce
while (digitalRead(EMERGENCY_BTN) == LOW) delay(10);
}
// 2) Read floor input
static String entry = "";
char k = keypad.getKey();
if (k) {
if (k >= '0' && k <= '9') {
if (entry.length() < 2) {
entry += k;
lcd.setCursor(0, 1);
lcd.print("Floor: " + entry + " ");
}
} else if (k == '#') {
if (entry.length() > 0) {
int dest = entry.toInt();
lcd.clear();
lcd.print("Target: " + String(dest));
delay(500);
if (dest == currentFloor) {
// fault
sendCommand(0x03, 0);
lcd.clear();
lcd.print("Fault!");
delay(1000);
} else {
// normal move
sendCommand(0x01, dest);
currentFloor = dest;
}
lcd.clear();
lcd.print("Choose floor:");
}
entry = "";
} else if (k == '*') {
entry = ""; // clear
lcd.setCursor(0, 1);
lcd.print(" ");
}
}
}
// helper: send 2-byte command to slave
void sendCommand(byte cmd, byte data) {
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(cmd);
Wire.write(data);
Wire.endTransmission();
}