#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED width,  in pixels
#define SCREEN_HEIGHT 64 // OLED height, in pixels
// create an OLED display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

#define RXD1 16  //sambung dengan V0T esp32cam
#define TXD1 17  //sambung dengan V0T esp32cam

#include <ESP32Servo.h>
Servo servo;

int led1 = 14;
int led2 = 27;
int led3 = 26;
int led4 = 25;
int button1 = 15;
int button2 = 2;
int input1;
int input2;
String input;
int x = 0;
int buz = 33;

void setup() {
  Serial.begin(115200);
  Serial1.begin(115200, SERIAL_8N1, RXD1, TXD1);
  if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("failed to start SSD1306 OLED"));
    while (1);
  }
  delay(2000);         // wait two seconds for initializing
  oled.clearDisplay(); // clear display

  servo.attach(32);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  pinMode(button2, INPUT_PULLUP);
  pinMode(buz, OUTPUT);
}

void loop() {
  int input1 = digitalRead(button1);
  int input2 = digitalRead(button2);

  if (input1 == LOW) {
    x = 1;
  }
  if (input2 == LOW) {
    x = 0;
  }
  
  if (x == 1) {
    digitalWrite(led4, LOW);
    while (Serial1.available()) {
      input = Serial1.readString();
      Serial.println(input);
    }
    if (input == "orange") {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW);
      digitalWrite(led4, LOW);
      servo.write(45);
      delay(500);
      tone (buz, 250, 250);
      delay(250);
      OLED(input);
    }
    if (input == "apple") {
      digitalWrite(led1, LOW);
      digitalWrite(led2, HIGH);
      digitalWrite(led4, LOW);
      servo.write(90);
      delay(500);
      tone (buz, 350, 250);
      delay(250);
      OLED(input);
    }
  }
  if (x == 0) {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led4, HIGH);
    servo.write(0);
    delay(500);
    OLED("");
  }
}

void OLED(String display) {
  oled.clearDisplay(); // clear display
  oled.setTextSize(1);         // set text size
  oled.setTextColor(WHITE);    // set text color
  oled.setCursor(0, 2);       // set position to display (x,y)
  oled.println(display); // set text
  oled.display();
}