/*
* ============================================================================
* DIGITAL TWIN - BAI DO XE THONG MINH (Smart Parking)
* Firmware ESP32 cho Wokwi | Giao thuc MQTT -> broker.emqx.io
* ============================================================================
*
* Phan cung (BOM):
* - ESP32 DevKit v1
* - 4x HC-SR04 : cam bien 4 o do (Slot 1..4)
* - 1x SG90 : barie (servo 0..90 do)
* - 1x LCD1602 : man hinh tai cong (I2C, dia chi 0x27)
* - 1x Button : GIA LAP quet the RFID (RC522 chua co tren Wokwi free)
*
* So do chan (xem them diagram.json):
* Slot1 HC-SR04 : TRIG=13 ECHO=34
* Slot2 HC-SR04 : TRIG=12 ECHO=35
* Slot3 HC-SR04 : TRIG=14 ECHO=36 (VP)
* Slot4 HC-SR04 : TRIG=27 ECHO=39 (VN)
* Servo SG90 : PWM =26
* LCD1602 I2C : SDA =21 SCL=22
* Button (RFID) : GPIO=25 (INPUT_PULLUP, noi xuong GND)
*
* Thu vien can (Wokwi Library Manager / libraries.txt):
* PubSubClient, ArduinoJson, LiquidCrystal I2C, ESP32Servo
* ============================================================================
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
// ---------------------------------------------------------------------------
// CAU HINH - PHAI TRUNG VOI WEB TWIN
// ---------------------------------------------------------------------------
const char* WIFI_SSID = "Wokwi-GUEST"; // WiFi ao cua Wokwi (khong mat khau)
const char* WIFI_PASS = "";
const char* MQTT_HOST = "broker.emqx.io"; // Public broker EMQX
const int MQTT_PORT = 1883; // TCP khong ma hoa (cho Wokwi)
// Namespace rieng de tranh dung nguoi khac tren broker cong cong.
// NEU DOI chuoi nay thi phai doi luon trong web/index.html (hang TOPIC_BASE).
#define TOPIC_BASE "twin/parking/ute7a3f"
const char* T_SLOTS = TOPIC_BASE "/slots"; // ESP32 -> Web: trang thai 4 o
const char* T_BARRIER = TOPIC_BASE "/barrier"; // ESP32 -> Web: trang thai barie
const char* T_ACCESS = TOPIC_BASE "/access"; // ESP32 -> Web: log quet the
const char* T_LCD = TOPIC_BASE "/lcd"; // ESP32 -> Web: noi dung LCD
const char* T_CMD = TOPIC_BASE "/cmd"; // Web -> ESP32: lenh dieu khien
// ---------------------------------------------------------------------------
// CHAN GPIO
// ---------------------------------------------------------------------------
const int TRIG[4] = {13, 12, 14, 27};
const int ECHO[4] = {34, 35, 36, 39};
const int PIN_SERVO = 26;
const int PIN_BUTTON = 25;
const float OCCUPIED_CM = 100.0; // < 100cm coi nhu co xe
// ---------------------------------------------------------------------------
// DOI TUONG & BIEN TRANG THAI
// ---------------------------------------------------------------------------
WiFiClient wifiClient;
PubSubClient mqtt(wifiClient);
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo barrier;
bool slotOccupied[4] = {false, false, false, false};
bool barrierOpen = false;
int validCards = 2; // 2 the hop le (gia lap)
int scanCounter = 0; // de luan phien ID the gia lap
unsigned long lastSense = 0;
unsigned long lastPublish = 0;
unsigned long barrierTimer = 0; // tu dong dong barie sau khi quet the
unsigned long lastButton = 0; // chong doi nut (debounce)
const unsigned long SENSE_EVERY = 300; // ms
const unsigned long PUBLISH_EVERY = 1000; // ms (gui dinh ky ngay ca khi khong doi)
const unsigned long AUTO_CLOSE_MS = 5000; // dong barie sau 5s
// ---------------------------------------------------------------------------
// HC-SR04: do khoang cach (cm)
// ---------------------------------------------------------------------------
float readDistanceCM(int trig, int echo) {
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
long dur = pulseIn(echo, HIGH, 30000); // timeout 30ms (~5m)
if (dur == 0) return 400.0; // khong co echo -> xa (trong)
return dur * 0.0343 / 2.0;
}
// ---------------------------------------------------------------------------
// BARIE
// ---------------------------------------------------------------------------
void setBarrier(bool open) {
barrierOpen = open;
barrier.write(open ? 90 : 0);
StaticJsonDocument<64> doc;
doc["state"] = open ? "open" : "closed";
char buf[64];
serializeJson(doc, buf);
mqtt.publish(T_BARRIER, buf, true); // retained
if (open) barrierTimer = millis();
}
// ---------------------------------------------------------------------------
// LCD
// ---------------------------------------------------------------------------
int freeSlots() {
int f = 0;
for (int i = 0; i < 4; i++) if (!slotOccupied[i]) f++;
return f;
}
void updateLCD(const char* l1, const char* l2) {
lcd.clear();
lcd.setCursor(0, 0); lcd.print(l1);
lcd.setCursor(0, 1); lcd.print(l2);
StaticJsonDocument<128> doc;
doc["line1"] = l1;
doc["line2"] = l2;
char buf[128];
serializeJson(doc, buf);
mqtt.publish(T_LCD, buf, true);
}
void showIdleLCD() {
int f = freeSlots();
char l2[17];
if (f == 0) snprintf(l2, sizeof(l2), "FULL - 0 slot");
else snprintf(l2, sizeof(l2), "Free: %d slot", f);
updateLCD("Smart Parking", l2);
}
// ---------------------------------------------------------------------------
// GIA LAP QUET THE RFID (nut bam)
// ---------------------------------------------------------------------------
void simulateCardScan() {
// Luan phien giua 2 the gia lap
const char* cardId = (scanCounter++ % 2 == 0) ? "A1B2C3D4" : "E5F6A7B8";
bool granted = (freeSlots() > 0); // het cho thi tu choi
StaticJsonDocument<128> doc;
doc["card"] = cardId;
doc["granted"] = granted;
doc["ts"] = millis();
char buf[128];
serializeJson(doc, buf);
mqtt.publish(T_ACCESS, buf);
if (granted) {
char l2[17];
snprintf(l2, sizeof(l2), "ID:%s", cardId);
updateLCD("Welcome!", l2);
setBarrier(true);
} else {
updateLCD("Parking FULL", "No entry");
}
}
// ---------------------------------------------------------------------------
// MQTT CALLBACK: nhan lenh tu Web
// ---------------------------------------------------------------------------
void onMessage(char* topic, byte* payload, unsigned int len) {
StaticJsonDocument<128> doc;
if (deserializeJson(doc, payload, len)) return;
const char* action = doc["action"] | "";
if (strcmp(action, "open") == 0) { setBarrier(true); updateLCD("Gate OPEN", "Welcome!"); }
else if (strcmp(action, "close") == 0) { setBarrier(false); showIdleLCD(); }
else if (strcmp(action, "scan") == 0) { simulateCardScan(); }
}
// ---------------------------------------------------------------------------
// KET NOI
// ---------------------------------------------------------------------------
void connectWiFi() {
WiFi.mode(WIFI_STA);
// Tren Wokwi PHAI chi dinh channel 6 thi moi noi duoc nhanh/on dinh.
WiFi.begin(WIFI_SSID, WIFI_PASS, 6);
lcd.clear(); lcd.print("WiFi connecting");
int tries = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(200); Serial.print(".");
if (++tries > 50) { // sau ~10s chua duoc thi thu lai
Serial.println("\nRetry WiFi...");
WiFi.disconnect(); delay(200);
WiFi.begin(WIFI_SSID, WIFI_PASS, 6);
tries = 0;
}
}
Serial.println("\nWiFi OK: " + WiFi.localIP().toString());
lcd.clear(); lcd.print("WiFi OK");
}
void connectMQTT() {
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setCallback(onMessage);
while (!mqtt.connected()) {
String cid = "esp32-parking-" + String((uint32_t)esp_random(), HEX);
lcd.clear(); lcd.print("MQTT connecting");
if (mqtt.connect(cid.c_str())) {
mqtt.subscribe(T_CMD);
Serial.println("MQTT OK, sub: " + String(T_CMD));
} else {
Serial.println("MQTT fail rc=" + String(mqtt.state()));
delay(1500);
}
}
}
// ---------------------------------------------------------------------------
// PUBLISH TRANG THAI 4 O
// ---------------------------------------------------------------------------
void publishSlots() {
StaticJsonDocument<128> doc;
doc["slot1"] = slotOccupied[0] ? 1 : 0;
doc["slot2"] = slotOccupied[1] ? 1 : 0;
doc["slot3"] = slotOccupied[2] ? 1 : 0;
doc["slot4"] = slotOccupied[3] ? 1 : 0;
doc["free"] = freeSlots();
char buf[128];
serializeJson(doc, buf);
mqtt.publish(T_SLOTS, buf, true);
}
// ---------------------------------------------------------------------------
// SETUP
// ---------------------------------------------------------------------------
void setup() {
Serial.begin(115200);
for (int i = 0; i < 4; i++) {
pinMode(TRIG[i], OUTPUT);
pinMode(ECHO[i], INPUT);
}
pinMode(PIN_BUTTON, INPUT_PULLUP);
Wire.begin(21, 22);
lcd.init();
lcd.backlight();
barrier.setPeriodHertz(50);
barrier.attach(PIN_SERVO, 500, 2400);
barrier.write(0);
connectWiFi();
connectMQTT();
publishSlots();
setBarrier(false);
showIdleLCD();
}
// ---------------------------------------------------------------------------
// LOOP
// ---------------------------------------------------------------------------
void loop() {
if (!mqtt.connected()) connectMQTT();
mqtt.loop();
unsigned long now = millis();
// Nut bam -> gia lap quet the (debounce 400ms)
if (digitalRead(PIN_BUTTON) == LOW && now - lastButton > 400) {
lastButton = now;
simulateCardScan();
}
// Doc 4 cam bien
if (now - lastSense > SENSE_EVERY) {
lastSense = now;
bool changed = false;
for (int i = 0; i < 4; i++) {
float d = readDistanceCM(TRIG[i], ECHO[i]);
bool occ = (d < OCCUPIED_CM);
if (occ != slotOccupied[i]) { slotOccupied[i] = occ; changed = true; }
}
if (changed) { publishSlots(); if (!barrierOpen) showIdleLCD(); }
}
// Gui dinh ky (giu web dong bo du khong doi)
if (now - lastPublish > PUBLISH_EVERY) {
lastPublish = now;
publishSlots();
}
// Tu dong dong barie sau khi quet the
if (barrierOpen && now - barrierTimer > AUTO_CLOSE_MS) {
setBarrier(false);
showIdleLCD();
}
}