2024年10月2日 星期三

WOKWI MQTT (DHT22 & 16*2 LCD & LED)

 WOKWI  MQTT (DHT22 & 16*2 LCD & LED)

const char* mqtt_server = "broker.mqttgo.io";
const char Pubtopic1[]  = "alex9ufo/temp";
const char Pubtopic2[]  = "alex9ufo/hum";
const char Subtopic1[]  = "alex9ufo/command";











WOKWI程式

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

const int DHT_PIN = 15;
const int LED = 2;

DHTesp dhtSensor;

#define I2C_ADDR    0x27
#define LCD_COLUMNS 20
#define LCD_LINES   4

LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);

// Update these with values suitable for your network.
const char* ssid =  "Wokwi-GUEST";   // your network SSID (name)
const char* password = "";   // your network password
//const char* mqtt_server = "broker.mqttdashboard.com";// choose your mqtt server
const char* mqtt_server = "broker.mqttgo.io";
//const char* mqtt_server = "test.mosquitto.org";

const char Pubtopic1[]  = "alex9ufo/temp";
const char Pubtopic2[]  = "alex9ufo/hum";
const char Subtopic1[]  = "alex9ufo/command";

WiFiClient espClient;
PubSubClient client(espClient);

long lastMsg = 0;
char msg[50];
int value = 0;

//=========================================================
void callback(char* topic, byte* payload, unsigned int length)
{
  Serial.print("Command from MQTT broker is : [");
  Serial.print(topic);
  Serial.print("]");
  Serial.println();
  Serial.print(" publish data is:");
  lcd.clear();
  String message="";
  {
    for(int i=0;i<length;i++)
    {
      Serial.print((char)payload[i]);  
      message +=(char)payload[i];

      lcd.setCursor(0, 0);
      lcd.print("alex9ufo LCD"); // Start Print text to Line 1
      lcd.setCursor(i, 1);
      lcd.write((char)payload[i]);
    }
  }
 
  //Serial.println(message);
  message.trim();

  if (message == "on") {
      digitalWrite(LED, LOW);  // Turn on the LED
      Serial.print("LED = on ");
  }

  if (message == "off" ) {
      digitalWrite(LED, HIGH); // Turn off the LED
      Serial.print("LED = off ");
  }

  Serial.println();
} //end callback
//=========================================================
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    //if you MQTT broker has clientID,username and password
    //please change following line to    if (client.connect(clientId,userName,passWord))
    if (client.connect(clientId.c_str()))
    {
      Serial.println("connected");
      //once connected to MQTT broker, subscribe command if any
      //client.subscribe("alex9ufo/Command");
      client.subscribe(Subtopic1);

    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 6 seconds before retrying
      delay(6000);
    }
  }
} //end reconnect()
//=========================================================
void setup_wifi() {
   delay(100);
  // We start by connecting to a WiFi network
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
      delay(500);
      Serial.print(".");
    }
  randomSeed(micros());
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//=========================================================


void setup() {
  Serial.begin(115200);
 
  pinMode(LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
 
  // Init
  lcd.init();
  lcd.backlight();

  // Print something
  lcd.setCursor(3, 0);
  lcd.print("Welcome to");
  lcd.setCursor(2, 1);
  lcd.print("lcd display");
  lcd.setCursor(5, 2);
  lcd.print("Simulator");
  lcd.setCursor(7, 3);
  lcd.print("Enjoy!");
}


void loop() {
    if (!client.connected()) {
    reconnect();
  }
  client.setCallback(callback);
  client.loop();
  unsigned long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    TempAndHumidity  data = dhtSensor.getTempAndHumidity();

    String temp = String(data.temperature, 2);
    Serial.print("Temperature: ");
    Serial.println(temp);
    client.publish("alex9ufo/temp", temp.c_str());
   
    String hum = String(data.humidity, 1);
    Serial.print("Humidity: ");
    Serial.println(hum);
    client.publish("alex9ufo/hum", hum.c_str());
  }
}

沒有留言:

張貼留言

WOKWI MQTT&Node-Red (DHT22 & 16*2 LCD & LED)

WOKWI MQTT&Node-Red  (DHT22 & 16*2 LCD & LED) 前一篇的延伸 https://alex9ufoexploer.blogspot.com/2024/10/wokwi-mqtt-dht22-162-lcd-led.h...