2024年7月27日 星期六

ESP32 MQTT – Publish DS18B20 Temperature Readings

 ESP32 MQTT – Publish DS18B20 Temperature Readings 



















WOKWI程式


#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <OneWire.h>
#include <DallasTemperature.h>

#define WLAN_SSID "Wokwi-GUEST"
#define WLAN_PASS ""

/************************* Adafruit.io Setup ***************************/
#define AIO_SERVER      "broker.hivemq.com"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    ""
#define AIO_KEY         ""
#define AIO_FEED_1      "alex9ufo/esp32/ds18b20/temperature"
// Raspberry Pi Mosquitto MQTT Broker
//#define MQTT_HOST IPAddress(192, 168, 1, XXX)
// For a cloud MQTT broker, type the domain name

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ***************************************/
// Setup feeds 'temp' and 'hmdt' for publishing.
Adafruit_MQTT_Publish tempPub = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME AIO_FEED_1);

// Setup a feed called 'onoff' for subscribing to changes to the ON/OFF button


// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;          
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
// Temperature value
float temp;

unsigned long lastMsg = 0;

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;
  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }
  Serial.print("Connecting to MQTT... ");
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 10 seconds...");
    mqtt.disconnect();
    delay(10000);  // wait 10 seconds
    retries--;
    if (retries == 0) {
      // basically die and wait for WDT to reset me
      while (1);
    }
  }
  Serial.println("MQTT Connected!");
}


void setup() {
  // Start the DS18B20 sensor
  sensors.begin();
 
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  // Connect to WiFi access point.
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(); Serial.println("WiFi connected");
  Serial.println("IP address: "); Serial.println(WiFi.localIP());
}


void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

  // this is our 'wait for incoming subscription packets and callback em' busy subloop
  // try to spend your time here:
  mqtt.processPackets(10000);
 
  // ping the server to keep the mqtt connection alive
  // NOT required if you are publishing once every KEEPALIVE seconds
 
  if(! mqtt.ping()) {
    mqtt.disconnect();
  }
 

  // Publish feeds
  unsigned long now = millis();
  if (now - lastMsg > 10000) {
    lastMsg = now;
    // New temperature readings
    sensors.requestTemperatures();
    // Temperature in Celsius degrees
    temp = sensors.getTempCByIndex(0);
    // Temperature in Fahrenheit degrees
    //temp = sensors.getTempFByIndex(0);

    Serial.println("Temperature: " +String(temp) + "°C");
    Serial.println("---");
    char strTemperature[20];
    sprintf(strTemperature, "%.1f", temp);
    tempPub.publish(strTemperature);

  }

}


Node-Red程式

[ { "id": "9a55977d9dd88494", "type": "mqtt in", "z": "72c4df790a4c757f", "name": "", "topic": "alex9ufo/esp32/ds18b20/temperature", "qos": "2", "datatype": "auto-detect", "broker": "2380dcc0d36d2c6a", "nl": false, "rap": true, "rh": 0, "inputs": 0, "x": 610, "y": 240, "wires": [ [ "ea3b6b36bf2cac5b" ] ] }, { "id": "ea3b6b36bf2cac5b", "type": "ui_gauge", "z": "72c4df790a4c757f", "name": "", "group": "4f4d1221d5fcd2d2", "order": 0, "width": 0, "height": 0, "gtype": "gage", "title": "gauge", "label": "°C", "format": "{{value}}", "min": "-55", "max": "125", "colors": [ "#00b500", "#e6e600", "#ca3838" ], "seg1": "25", "seg2": "50", "className": "", "x": 870, "y": 240, "wires": [] }, { "id": "2380dcc0d36d2c6a", "type": "mqtt-broker", "name": "", "broker": "broker.hivemq.com", "port": "1883", "clientid": "", "autoConnect": true, "usetls": false, "protocolVersion": "4", "keepalive": "60", "cleansession": true, "birthTopic": "", "birthQos": "0", "birthPayload": "", "birthMsg": {}, "closeTopic": "", "closeQos": "0", "closePayload": "", "closeMsg": {}, "willTopic": "", "willQos": "0", "willPayload": "", "willMsg": {}, "userProps": "", "sessionExpiry": "" }, { "id": "4f4d1221d5fcd2d2", "type": "ui_group", "name": "溫度", "tab": "096dc3f20d4aa28b", "order": 1, "disp": true, "width": "6", "collapse": false, "className": "" }, { "id": "096dc3f20d4aa28b", "type": "ui_tab", "name": "MQTT DS18B20", "icon": "dashboard", "order": 128, "disabled": false, "hidden": false } ]


2024年7月24日 星期三

MIT Inventor / WOKWI 4 LED Control / MQTT

MIT Inventor / WOKWI 4 LED Control / MQTT























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

//Relays for switching appliances
#define Relay1            15     //D15 LED-Orangs = Water-1
#define Relay2            2     //D2   LED-Blue  = Water-2
#define Relay3            19    //D19  LED-Blue   = Motor
#define Relay4            23    //D23  LED-RED    = Fan

//Nenu For Control
int menu;

//Changs to:
#define sub1 "alex9ufo/SWcnt1"
#define sub2 "alex9ufo/SWcnt2"
#define sub3 "alex9ufo/SWcnt3"
#define sub4 "alex9ufo/SWcnt4"
const char pubTopic[] = "alex9ufo/lights";

// 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.hivemq.com";
const char* username = "";
const char* pass = "";

WiFiClient espClient;
PubSubClient client(espClient);

unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
String onoffMsg="";
//=====================================================================
void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  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 callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String messageTemp;
  for(int i=0; i<length; i+=1) {
    messageTemp += (char)payload[i];
  }
  messageTemp.trim();
  Serial.println(messageTemp);
 
  if (String(topic)=="alex9ufo/SWcnt1") {
      if(messageTemp=="ON"){
        Serial.println("Led1 ON");
        digitalWrite(Relay1,HIGH);
        onoffMsg="11";
      }  
      if(messageTemp=="OFF"){
        Serial.println("Led1 OFF");
        digitalWrite(Relay1,LOW);
        onoffMsg="10";
      }
  }
  if (String(topic)=="alex9ufo/SWcnt2") {
      if(messageTemp=="ON"){
        Serial.println("Led2 ON");
        digitalWrite(Relay2,HIGH);
        onoffMsg="21";
      }  
      if(messageTemp=="OFF"){
        Serial.println("Led2 OFF");
        digitalWrite(Relay2,LOW);
        onoffMsg="20";
      }
  }

  if (String(topic)=="alex9ufo/SWcnt3") {
      if(messageTemp=="ON"){
        Serial.println("Led3 ON");
        digitalWrite(Relay3,HIGH);
        onoffMsg="31";
      }  
      if(messageTemp=="OFF"){
        Serial.println("Led3 OFF");
        digitalWrite(Relay3,LOW);
        onoffMsg="30";          
      }
  }

  if (String(topic)=="alex9ufo/SWcnt4") {
      if(messageTemp=="ON"){
        Serial.println("Led4 ON");
        digitalWrite(Relay4,HIGH);
        onoffMsg="41";
      }  
      if(messageTemp=="OFF"){
        Serial.println("Led4 OFF");
        digitalWrite(Relay4,LOW);
        onoffMsg="40";
      }
  }

}
//=====================================================================
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), username, pass) ) {
      Serial.println("connected");
      client.subscribe(sub1);
      client.subscribe(sub2);
      client.subscribe(sub3);
      client.subscribe(sub4);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//=====================================================================
void setup() {
  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
  pinMode(Relay3, OUTPUT);
  pinMode(Relay4, OUTPUT);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  client.subscribe(sub1);
  client.subscribe(sub2);
  client.subscribe(sub3);
  client.subscribe(sub4);

}
//=====================================================================
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  //=========================================
  if (onoffMsg=="10") {
      String msgStr = "10";
      byte arrSize = msgStr.length() + 1;
      char msg[arrSize];

      Serial.print("PUBLISH DATA: LED");
      Serial.println(msgStr);
      msgStr.toCharArray(msg, arrSize);
      client.publish(pubTopic, msg);
      onoffMsg= "";
      delay(50);
  }
  if (onoffMsg=="11") {
      String msgStr = "11";
      byte arrSize = msgStr.length() + 1;
      char msg[arrSize];

      Serial.print("PUBLISH DATA: LED");
      Serial.println(msgStr);
      msgStr.toCharArray(msg, arrSize);
      client.publish(pubTopic, msg);
      onoffMsg= "";
      delay(50);
  }
  //=========================================
 if (onoffMsg=="20") {
      String msgStr = "20";
      byte arrSize = msgStr.length() + 1;
      char msg[arrSize];

      Serial.print("PUBLISH DATA: LED");
      Serial.println(msgStr);
      msgStr.toCharArray(msg, arrSize);
      client.publish(pubTopic, msg);
      onoffMsg= "";
      delay(50);
  }
  if (onoffMsg=="21") {
      String msgStr = "21";
      byte arrSize = msgStr.length() + 1;
      char msg[arrSize];

      Serial.print("PUBLISH DATA: LED");
      Serial.println(msgStr);
      msgStr.toCharArray(msg, arrSize);
      client.publish(pubTopic, msg);
      onoffMsg= "";
      delay(50);
  }
 //=========================================
 if (onoffMsg=="30") {
      String msgStr = "30";
      byte arrSize = msgStr.length() + 1;
      char msg[arrSize];

      Serial.print("PUBLISH DATA: LED");
      Serial.println(msgStr);
      msgStr.toCharArray(msg, arrSize);
      client.publish(pubTopic, msg);
      onoffMsg= "";
      delay(50);
  }
  if (onoffMsg=="31") {
      String msgStr = "31";
      byte arrSize = msgStr.length() + 1;
      char msg[arrSize];

      Serial.print("PUBLISH DATA: LED");
      Serial.println(msgStr);
      msgStr.toCharArray(msg, arrSize);
      client.publish(pubTopic, msg);
      onoffMsg= "";
      delay(50);
  }
  //=========================================
 if (onoffMsg=="40") {
      String msgStr = "40";
      byte arrSize = msgStr.length() + 1;
      char msg[arrSize];

      Serial.print("PUBLISH DATA: LED");
      Serial.println(msgStr);
      msgStr.toCharArray(msg, arrSize);
      client.publish(pubTopic, msg);
      onoffMsg= "";
      delay(50);
  }
  if (onoffMsg=="41") {
      String msgStr = "41";
      byte arrSize = msgStr.length() + 1;
      char msg[arrSize];

      Serial.print("PUBLISH DATA: LED");
      Serial.println(msgStr);
      msgStr.toCharArray(msg, arrSize);
      client.publish(pubTopic, msg);
      onoffMsg= "";
      delay(50);
  }

}
//=====================================================================

2024年7月22日 星期一

LED TEMPERATURE HUMIDITY APK Ver2.0 (ESP32. MQTT. Broker. Publish. Subscribe .MIT APP Inventor)

 LED TEMPERATURE HUMIDITY APK Ver2.0  (ESP32. MQTT. Broker. Publish. Subscribe .MIT APP Inventor)


參考來源 https://github.com/HighVoltages/Mqtt-in-Android-app---mit-app-inventor















MIT INVENTOR 程式

https://drive.google.com/file/d/1y1DJz7S6jgSd-jSFo_LUMlmXKUTHnkvP/view?usp=sharing



WOKWI程式

#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <DHTesp.h>

//
const int DHTPIN = 15;
const int LED = 13;

DHTesp dhtSensor;

uint32_t delayMS;

const char* ssid = "Wokwi-GUEST";
const char* password = "";

const char *mqtt_broker = "broker.hivemq.com";
const int mqtt_port = 1883;


//MQTT Credentials
const char* topic = "alex9ufo/Tempdata"; //publish topic

//parameters for using non-blocking delay
unsigned long previousMillis = 0;
const long interval = 5000;

String msgStr = "";      // MQTT message buffer
float temp, hum;

//setting up wifi and mqtt client
WiFiClient espClient;
PubSubClient client(espClient);
//=============================================================================
void setup_wifi() {
  delay(10);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//=============================================================================
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 (client.connect(clientId.c_str())) {
      Serial.println("Connected");
      // Once connected, publish an announcement...
      //client.publish("alex9ufo/esp32", "iotfrontier");

      // ... and resubscribe
      client.subscribe("alex9ufo/lights");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//=============================================================================
//subscribe call back
void callback(char*topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  String data = "";
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    data += (char)payload[i];
  }
  Serial.println();
  Serial.print("Message size :");
  Serial.println(length);
  Serial.println();
  Serial.println("-----------------------");
  Serial.println(data);
  if(data=="ON"){
    Serial.println("LED =on");
    digitalWrite(LED,LOW );
  }
  else{
    Serial.println("LED =off");
    digitalWrite(LED,HIGH );
  }
}
//=============================================================================
void setup() {
  Serial.begin(115200);
  // Initialize device.
  dhtSensor.setup(DHTPIN, DHTesp::DHT22);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);

  setup_wifi();

  client.setServer(mqtt_broker , 1883); //setting MQTT server
  client.setCallback(callback); //defining function which will be called when message is recieved.

}
//=============================================================================
void loop() {
  if (!client.connected()) { //if client is not connected
    reconnect(); //try to reconnect
  }
  client.loop();

  unsigned long currentMillis = millis(); //read current time

  if (currentMillis - previousMillis >= interval) { //if current time - last time > 5 sec
    previousMillis = currentMillis;

    TempAndHumidity  data = dhtSensor.getTempAndHumidity();

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

    msgStr = String(temp) +","+String(hum);
    byte arrSize = msgStr.length() + 1;
    char msg[arrSize];

    Serial.print("PUBLISH DATA:");
    Serial.println(msgStr);
    msgStr.toCharArray(msg, arrSize);
    client.publish(topic, msg);
    msgStr = "";
    delay(50);

  }

}
//=============================================================================

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...