#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Inisialisasi LCD 16x2 dengan I2C
LiquidCrystal_I2C lcd(0x27, 16, 2);

// Pin untuk push button
const int buttonForward = 7;
const int buttonReverse = 6;
const int buttonStop = 5;

// Pin untuk relay
const int relay1 = 8;
const int relay2 = 9;

// Status motor
enum MotorStatus {
  STOPPED,
  FORWARD,
  REVERSE
};

MotorStatus motorStatus = STOPPED;
bool displayStartMessage = true;  // Flag untuk menampilkan pesan "Press Start"

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.clear();  // Membersihkan layar LCD

  lcd.setCursor(0, 0);
  lcd.print("Motor Control");

  pinMode(buttonForward, INPUT_PULLUP);
  pinMode(buttonReverse, INPUT_PULLUP);
  pinMode(buttonStop, INPUT_PULLUP);

  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);

  // Matikan relay awal
  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);
}

void loop() {
  // Baca status tombol dan kontrol motor
  readButtons();
  controlMotor();

  // Tampilkan status pada LCD
  displayStatus();
}

void readButtons() {
  static unsigned long lastButtonPressTime = 0;
  unsigned long currentMillis = millis();

  // Debounce interval
  if (currentMillis - lastButtonPressTime < 200) {
    return;
  }

  // Tombol forward
  if (digitalRead(buttonForward) == LOW && motorStatus == STOPPED) {
    motorStatus = FORWARD;
    lastButtonPressTime = currentMillis;
    displayStartMessage = false;
  }

  // Tombol reverse
  if (digitalRead(buttonReverse) == LOW && motorStatus == STOPPED) {
    motorStatus = REVERSE;
    lastButtonPressTime = currentMillis;
    displayStartMessage = false;
  }

  // Tombol stop
  if (digitalRead(buttonStop) == LOW) {
    motorStatus = STOPPED;
    lastButtonPressTime = currentMillis;
    displayStartMessage = true;
  }
}

void controlMotor() {
  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);

  switch (motorStatus) {
    case FORWARD:
      digitalWrite(relay1, HIGH);
      break;
    case REVERSE:
      digitalWrite(relay2, HIGH);
      break;
  }
}

void displayStatus() {
  lcd.setCursor(0, 1);

  if (displayStartMessage) {
    lcd.print("Status: STOPPED        ");
  } else {
    switch (motorStatus) {
      case STOPPED:
        lcd.print("");
        break;
      case FORWARD:
        lcd.print("Status: FORWARD        ");
        break;
      case REVERSE:
        lcd.print("Status: REVERSE        ");
        break;
    }
  }
}
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module