2024年6月5日 星期三

WOKWI ESP32 DHT22 + ThinkSpeak +MQTT

 WOKWI ESP32  DHT22 + ThinkSpeak +MQTT 














WoKWI 程式

#include <WiFi.h>

#include "DHTesp.h"
#include "ThingSpeak.h"
#include <ArduinoMqttClient.h>


//WiFiClient wifiClient - creates a Wi-Fi client.
//MqttClient mqttClient(wifiClient) - connects the Wi-Fi client to the MQTT client.
//WiFi.begin(ssid, pass) - connects to local Wi-Fi network.
//mqttClient.connect(broker, port) - connects to broker (and port).
//mqttClient.poll() - keeps the connection alive, used in the loop().
//mqttClient.beginMessage(topic) - creates a new message to be published.
//mqttClient.print() - prints the content of message between the ().
//mqttClient.endMessage() - publishes the message to the broker.
//mqttClient.subscribe(topic) - subscribes to a topic.
//mqttClient.available() - checks if any messages are available from the topic.
//mqttClient.read() - reads the incoming messages.

const int DHT_PIN = 15;
const int LED_PIN = 13;

const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";

const int myChannelNumber = 622462;
const char* myApiKey = "8U11H22OD8L4P9L718";
const char* server = "api.thingspeak.com";

unsigned long previousMillis = 0;
unsigned long interval = 10000;

DHTesp dhtSensor;

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

//const char broker[] = "test.mosquitto.org";
const char broker[] = "broker.emqx.io";
int        port     = 1883;

const char *PubTopic1 = "alex9ufo/DHT22/Temp";
const char *PubTopic2 = "alex9ufo/DHT22/Humi";

const char *SubTopic1 = "alex9ufo/DHT22/Temp";

const char willTopic[] = "alex9ufo/Starting";

String json1 = "";
String json2 = "";

//===========================================================
void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.print("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  String Topic= mqttClient.messageTopic();
  Serial.print("', duplicate = ");
  Serial.print(mqttClient.messageDup() ? "true" : "false");
  Serial.print(", QoS = ");
  Serial.print(mqttClient.messageQoS());
  Serial.print(", retained = ");
  Serial.print(mqttClient.messageRetain() ? "true" : "false");
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");
  String message="";
  // use the Stream interface to print the contents
  while (mqttClient.available()) {
    //Serial.print((char)mqttClient.read());
    message += (char)mqttClient.read();
  }

  Serial.println(message);
  message.trim();
  Topic.trim();
 
  Serial.println();
  Serial.println("-----------------------");

}
//===========================================================
//副程式  setup wifi
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WIFI_NAME);     //print ssid
  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }   //假設 wifi 未連接 show ………

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}  
//===========================================================
void setup() {
  Serial.begin(115200);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

  setup_wifi();
  Serial.println("You're connected to the network");
  Serial.println();

  //WiFi.mode(WIFI_STA);
  ThingSpeak.begin(wifiClient);

  String willPayload = "ESP32 Start working....!";
  bool willRetain = true;
  int willQos = 1;

  mqttClient.beginWill(willTopic, willPayload.length(), willRetain, willQos);
  mqttClient.print(willPayload);
  mqttClient.endWill();

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();

  // set the message receive callback
  mqttClient.onMessage(onMqttMessage);
  Serial.print("Subscribing to topic: ");
  Serial.println(SubTopic1);
 
  // subscribe to a topic
  // the second parameter sets the QoS of the subscription,
  // the the library supports subscribing at QoS 0, 1, or 2
  int subscribeQos = 1;
  mqttClient.subscribe(SubTopic1, subscribeQos);

  Serial.println();
  delay(4);       // Optional delay. Some board do need more time after init to be ready, see Readme
}
//===========================================================
void loop() {
  // call poll() regularly to allow the library to send MQTT keep alive which
  // avoids being disconnected by the broker
  mqttClient.poll();

  unsigned long currentMillis = millis();


  if (currentMillis - previousMillis >=interval) {
  int randNumber1 = random(1, 25);
  int randNumber2 = random(5, 9);
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  ThingSpeak.setField(1,data.temperature+randNumber1);
  ThingSpeak.setField(2,data.humidity+randNumber2);

 
  //if (mqttClient.available()) {
    bool retained = false;
    int qos = 1;
    bool dup = false;
 
    json1=String(data.temperature+randNumber1, 2);
    mqttClient.beginMessage(PubTopic1,  json1.length(), retained, qos, dup);
    mqttClient.print(json1);
    mqttClient.endMessage();
    Serial.print(PubTopic1);
    Serial.println(json1);
    delay(1000);

    json2=String(data.humidity+randNumber2, 1);
    mqttClient.beginMessage(PubTopic2,  json2.length(), retained, qos, dup);
    mqttClient.print(json2);
    mqttClient.endMessage();
    Serial.print(PubTopic2);
    Serial.println(json2);
  //}




  if (data.temperature+randNumber1 > 35 || data.temperature+randNumber1 < 12 || data.humidity+randNumber2 > 70 || data.humidity+randNumber2 < 40) {
    digitalWrite(LED_PIN, LOW);
  }else{
    digitalWrite(LED_PIN, HIGH);
  }
 
  int x = ThingSpeak.writeFields(myChannelNumber,myApiKey);
 
  Serial.println("Temp: " + String(data.temperature+randNumber1, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity+randNumber2, 1) + "%");
 
  if(x == 200){
    Serial.println("Data pushed successfull");
  }else{
    Serial.println("Push error" + String(x));
  }
  Serial.println("---");
 

  previousMillis = currentMillis;
  }
  /* ... */
  if (!mqttClient.connected()) {
    Serial.println("MQTT connection lost");
    if (!mqttClient.connect(broker, port)) {
      Serial.print("MQTT reconnection error ");
      Serial.println(mqttClient.connectError());
    }
  }
}


Node-Red程式

[{"id":"8942955725c21648","type":"ui_artlessgauge","z":"eb00260d98e4aedd","group":"4106d37f66ef0cff","order":1,"width":6,"height":4,"name":"","icon":"","label":"溫度","unit":"℃","layout":"radial","decimals":0,"differential":false,"minmax":false,"colorTrack":"#555555","style":"","colorFromTheme":true,"property":"payload","secondary":"secondary","inline":false,"animate":true,"sectors":[{"val":0,"col":"#ff9900","t":"min","dot":0},{"val":60,"col":"#ff9900","t":"max","dot":0}],"lineWidth":3,"bgcolorFromTheme":true,"diffCenter":"","x":960,"y":120,"wires":[]},{"id":"2eef2e6979a29b0c","type":"mqtt in","z":"eb00260d98e4aedd","name":"Temp","topic":"alex9ufo/DHT22/Temp","qos":"1","datatype":"auto-detect","broker":"dce5aa632b12c4cc","nl":false,"rap":true,"rh":0,"inputs":0,"x":690,"y":120,"wires":[["8942955725c21648"]]},{"id":"90481ff2ce0ba72f","type":"ui_artlessgauge","z":"eb00260d98e4aedd","group":"4106d37f66ef0cff","order":2,"width":6,"height":4,"name":"","icon":"","label":"濕度","unit":"%","layout":"radial","decimals":0,"differential":false,"minmax":false,"colorTrack":"#555555","style":"","colorFromTheme":true,"property":"payload","secondary":"secondary","inline":false,"animate":true,"sectors":[{"val":0,"col":"#00ff4c","t":"min","dot":0},{"val":100,"col":"#00ff4c","t":"max","dot":0}],"lineWidth":"9","bgcolorFromTheme":true,"diffCenter":"","x":960,"y":180,"wires":[]},{"id":"c8a33e8859ffe0eb","type":"mqtt in","z":"eb00260d98e4aedd","name":"Humi","topic":"alex9ufo/DHT22/Humi","qos":"1","datatype":"auto-detect","broker":"dce5aa632b12c4cc","nl":false,"rap":true,"rh":0,"inputs":0,"x":690,"y":180,"wires":[["90481ff2ce0ba72f"]]},{"id":"4106d37f66ef0cff","type":"ui_group","name":"MQTT Basic4","tab":"2eed7cc3b24b8f69","order":5,"disp":true,"width":"6","collapse":false,"className":""},{"id":"dce5aa632b12c4cc","type":"mqtt-broker","name":"EMQx","broker":"broker.emqx.io","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"5","keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"2eed7cc3b24b8f69","type":"ui_tab","name":"WOKWI_LED","icon":"dashboard","order":125,"disabled":false,"hidden":false}]

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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