MQTT LCD Motion Receiver — ESP32 simulation

Raspberry Pi MQTT motion sensor receiver with I2C LCD display

An interactive ESP32 circuit simulation you can run free in your browser on Velxio, by tarazan88889.

Components

Sketch code

#include <WiFi.h>
#include <PubSubClient.h>
#include <LiquidCrystal_I2C.h>

WiFiClient espClient;
PubSubClient client(espClient);
LiquidCrystal_I2C lcd(0x27, 16, 2);

void onMessage(char* topic, byte* payload, unsigned int length) {
  String msg = "";
  for (unsigned int i = 0; i < length; i++) msg += (char)payload[i];
  Serial.println("RX: " + msg);

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Motion Detected:");
  lcd.setCursor(0, 1);
  lcd.print(msg);
}

void setup() {
  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  lcd.print("Connecting...");

  WiFi.begin("Velxio-GUEST");
  while (WiFi.status() != WL_CONNECTED) delay(500);
  Serial.println("WiFi OK");
  lcd.clear(); lcd.print("WiFi OK");

  client.setServer("35.157.128.15", 1883);
  client.setCallback(onMessage);

  while (!client.connected()) {
    if (client.connect("gateway_lcd")) {
      Serial.println("MQTT OK");
      client.subscribe("home/bathroom/motion");
      client.subscribe("home/bedroom/motion");
      client.subscribe("home/living_room/motion");
      lcd.clear(); lcd.print("Monitoring...");
    } else {
      delay(2000);
    }
  }
}

void loop() {
  client.loop();
}