#include <WiFi.h>
#include <ESP32Servo.h>
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
WiFiClient client;
Servo myservo1;
Servo myservo2;
Servo myservo3;
Servo myservo4;
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "................"   // AIO Key
#define AIO_KEY "......................"  // AIO password
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Subscribe servo = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/servo");
int kode = 0;
void setup() {
  Serial.begin(115200);
  WiFi.begin("Wokwi-GUEST", "");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  lcd.init();
  lcd.backlight();
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Coin Sorting ESP");
  mqtt.subscribe(&servo);
  myservo1.attach(19);
  myservo2.attach(18);
  myservo3.attach(5);
  myservo4.attach(17);
}
void loop() {
  MQTT_connect();
  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &servo) {
      kode = atoi((char *)servo.lastread);
      Serial.println(kode);
      if (kode == 1) {
        lcd.setCursor(0, 1);
        lcd.print("Coin 100 -> Srv1");
        myservo1.write(180);
        delay(100);
      }
      if (kode != 1) {
        myservo1.write(0);
        delay(100);
      }
      if (kode == 2) {
        lcd.setCursor(0, 1);
        lcd.print("Coin 200 -> Srv2");
        myservo2.write(180);
        delay(100);
      }
      if (kode != 2) {
        myservo2.write(0);
        delay(100);
      }
      if (kode == 3) {
        lcd.setCursor(0, 1);
        lcd.print("Coin 500 -> Srv3");
        myservo3.write(180);
        delay(100);
      }
      if (kode != 3) {
        myservo3.write(0);
        delay(100);
      }
      if (kode == 4) {
        lcd.setCursor(0, 1);
        lcd.print("Coin 1000-> Srv4");
        myservo4.write(180);
        delay(100);
      }
      if (kode != 4) {
        myservo4.write(0);
        delay(100);
      }
      if (kode == 0) {
        lcd.setCursor(0, 1);
        lcd.print("No coin detected");
      }
    }
  }
}
void MQTT_connect() {
  int8_t ret;
  if (mqtt.connected()) {
    return;
  }
  Serial.print("Connecting to MQTT... ");
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) {
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 5 seconds...");
    mqtt.disconnect();
    delay(5000);  // wait 5 seconds
    retries--;
    if (retries == 0) {
      while (1);
    }
  }
  Serial.println("MQTT Connected!");
}
100
200
500
1000