2025年1月29日 星期三

ESP32 Control 4 RELAY by Node-Red MQTT

 ESP32 Control 4 RELAY by Node-Red MQTT







WOKWI程式

#include <WiFi.h>
#include <PubSubClient.h> //請先安裝PubSubClient程式庫
// ------ 以下修改成你自己的WiFi帳號密碼 ------
char* ssid = "Wokwi-GUEST"; //請修改為您連線的網路名稱
char* password = ""; //請修改為您連線的網路密碼
// ------ 以下修改成你MQTT設定 ------
char* MQTTServer = "mqttgo.io";//免註冊MQTT伺服器
int MQTTPort = 1883;//MQTT Port 除非加密,否則不用更改port
char* MQTTUser = "";//不須帳密
char* MQTTPassword = "";//不須帳密


// Topics 訂閱主題1:訂閱訊息(記得改Topic)
const char* relay_topic = "alex9ufo/esp32/relay";
char* MQTTPubTopic1 = "alex9ufo/esp32/relay_back";

// Relay pins
const int relay1 = 23;  //繼電器1 ON =亮
const int relay2 = 22;  //繼電器2 ON =亮
const int relay3 = 21;  //繼電器3 ON =亮
const int relay4 = 19;  //繼電器4 ON =亮

//建立MQTT與聯網物件
WiFiClient WifiClient;
PubSubClient MQTTClient(WifiClient);

//建立變數資料
int num=1234567890;
//==========================================================
// Callback function
void callback(char* topic, byte* payload, unsigned int length) {
  payload[length] = '\0';
  String message = String((char*)payload);
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  Serial.println( message);

  if (String(topic) == relay_topic) {
  // Control relay
  if (message == "OFF1")
    digitalWrite(relay1, LOW); // LOW to activate
    MQTTClient.publish(MQTTPubTopic1,message.c_str());
    Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
    Serial.println(message);
  if (message == "ON1")
    digitalWrite(relay1, HIGH);
    MQTTClient.publish(MQTTPubTopic1,message.c_str());
    Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
    Serial.println(message);
  if (message == "OFF2")
    digitalWrite(relay2, LOW);
    MQTTClient.publish(MQTTPubTopic1,message.c_str());
    Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
    Serial.println(message);
  if (message == "ON2")
    digitalWrite(relay2, HIGH);
    MQTTClient.publish(MQTTPubTopic1,message.c_str());
    Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
    Serial.println(message);
  if (message == "OFF3")
    digitalWrite(relay3, LOW);
    MQTTClient.publish(MQTTPubTopic1,message.c_str());
    Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
    Serial.println(message);
  if (message == "ON3")
    digitalWrite(relay3, HIGH);
    MQTTClient.publish(MQTTPubTopic1,message.c_str());
    Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
    Serial.println(message);
  if (message == "OFF4")
    digitalWrite(relay4, LOW);
    MQTTClient.publish(MQTTPubTopic1,message.c_str());
    Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
    Serial.println(message);
  if (message == "ON4")
    digitalWrite(relay4, HIGH);
    MQTTClient.publish(MQTTPubTopic1,message.c_str());
    Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
    Serial.println(message);
  if (message == "ALLON")
    {
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      MQTTClient.publish(MQTTPubTopic1,message.c_str());
      Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
      Serial.println(message);
    }

  if (message == "ALLOFF")
    {
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      MQTTClient.publish(MQTTPubTopic1,message.c_str());
      Serial.print( "Published Topic:alex9ufo/esp32/relay_back-->");
      Serial.println(message);
    }
  }
}
//==========================================================
//開始WiFi連線
void WifiConnecte() {
  //開始WiFi連線
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi連線成功");
  Serial.print("IP Address:");
  Serial.println(WiFi.localIP());
}
//==========================================================
//開始MQTT連線
void MQTTConnecte() {
  MQTTClient.setServer(MQTTServer, MQTTPort);
  while (!MQTTClient.connected()) {
    //以亂數為ClietID
    String  MQTTClientid = "esp32-" + String(random(1000000, 9999999));//建立一個id,MQTT要求id要不一樣,所以使用亂數
    if (MQTTClient.connect(MQTTClientid.c_str(), MQTTUser, MQTTPassword)) {
      //連結成功,顯示「已連線」。
      Serial.println("MQTT已連線");
    } else {
      //若連線不成功,則顯示錯誤訊息,並重新連線
      Serial.print("MQTT連線失敗,狀態碼=");
      Serial.println(MQTTClient.state());
      Serial.println("五秒後重新連線");
      delay(5000);
    }
  }
}
//==========================================================
//==========================================================
void setup() {
  Serial.begin(115200);
  Serial.begin(115200);

  pinMode(relay1, OUTPUT);  //輸出模式
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);

  digitalWrite(relay1, LOW);  //LED熄滅
  digitalWrite(relay2, LOW);
  digitalWrite(relay3, LOW);
  digitalWrite(relay4, LOW);

  //開始WiFi連線
  WifiConnecte();
  //開始MQTT連線
  MQTTConnecte();

  MQTTClient.setCallback(callback);
  MQTTClient.subscribe(relay_topic);  
}
//==========================================================
void loop() {
  //如果WiFi連線中斷,則重啟WiFi連線
  if (WiFi.status() != WL_CONNECTED) { WifiConnecte(); }

  //如果MQTT連線中斷,則重啟MQTT連線
  if (!MQTTClient.connected()) {  MQTTConnecte(); }

  MQTTClient.loop();//更新訂閱狀態
  delay(50);
}
//==========================================================

WOKWI DHT22 & LED (Node-Red)20250129160156

2025年1月27日 星期一

WOKWI DHT22 & LED (Node-Red)

 WOKWI DHT22 & LED (Node-Red)





WOKWI程式
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"

const int DHT_PIN = 15;
const int LED_PIN = 12;

DHTesp dhtSensor;

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";
const char *SubTopic1 = "ale9ufo/mqtt/led";
const char *PubTopic1 = "ale9ufo/mqtt/temp";
const char *PubTopic2 = "ale9ufo/mqtt/hum";


WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE  (50)
float temp = 0;
float hum = 0;
int value = 0;

String LEDjson = "";
bool Flash = false;  //true
//=========================================================================
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++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }

  if (strcmp(topic, SubTopic1) == 0) {
    // If the relay is on turn it off (and vice-versa)
    Serial.println();
    Serial.println(messageTemp);  
   
    if (messageTemp == "on") {
      digitalWrite(LED_PIN, HIGH);  // Turn on the LED
      //ledState = true;  //ledState = ture HIGH
      //設定 各個 旗號
      LEDjson ="ON";
      Flash = false;
      Serial.print("LED =");
      Serial.println(LEDjson);
    }

    if (messageTemp == "off" ) {
      digitalWrite(LED_PIN , LOW); // Turn off the LED
      //ledState = false; //ledState = false LOW
      LEDjson ="OFF";
      Flash = false;
      Serial.print("LED =");
      Serial.println(LEDjson);
    }
 
    if (messageTemp == "flash" ) {
      digitalWrite(LED_PIN, HIGH); // Turn off the LED
      Flash = true;
      LEDjson ="FLASH";
      Serial.print("LED =");
      Serial.println(LEDjson);      
    }
  }
}
//=========================================================================
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("ale9ufo/mqtt", "Indobot");
      // ... and resubscribe
      client.subscribe(SubTopic1);
    } 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(LED_PIN, OUTPUT);     // Initialize the BUILTIN_LED pin as an output

  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  client.subscribe(SubTopic1);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}
//=========================================================================
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
 
  if (Flash){
    digitalWrite(LED_PIN, !digitalRead(LED_PIN));
    delay(250);
  } //(Flash)

  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(PubTopic1, temp.c_str());
   
    String hum = String(data.humidity, 1);
    Serial.print("Humidity: ");
    Serial.println(hum);
    client.publish(PubTopic2, hum.c_str());
  }
}
//=========================================================================

Node-Red程式
[ { "id": "ba42d4b5dbf8aef2", "type": "ui_led", "z": "551bcfad002a399e", "order": 4, "group": "025f9ffb9a6ef09a", "width": 6, "height": 3, "label": "", "labelPlacement": "left", "labelAlignment": "left", "colorForValue": [ { "color": "#ff0000", "value": "false", "valueType": "bool" }, { "color": "#008000", "value": "true", "valueType": "bool" } ], "allowColorForValueInMessage": false, "shape": "circle", "showGlow": true, "name": "", "x": 530, "y": 740, "wires": [] }, { "id": "19dba15641b16f18", "type": "ui_button", "z": "551bcfad002a399e", "name": "", "group": "025f9ffb9a6ef09a", "order": 1, "width": 2, "height": 1, "passthru": false, "label": "ON", "tooltip": "", "color": "", "bgcolor": "", "className": "", "icon": "", "payload": "on", "payloadType": "str", "topic": "topic", "topicType": "msg", "x": 70, "y": 620, "wires": [ [ "364f12c3e131bf5a", "cc1b11b1.bebb28" ] ] }, { "id": "10c57c6d4f586617", "type": "ui_button", "z": "551bcfad002a399e", "name": "", "group": "025f9ffb9a6ef09a", "order": 2, "width": 2, "height": 1, "passthru": false, "label": "OFF", "tooltip": "", "color": "", "bgcolor": "", "className": "", "icon": "", "payload": "off", "payloadType": "str", "topic": "topic", "topicType": "msg", "x": 70, "y": 680, "wires": [ [ "364f12c3e131bf5a", "cc1b11b1.bebb28" ] ] }, { "id": "84e38b3103221443", "type": "ui_button", "z": "551bcfad002a399e", "name": "", "group": "025f9ffb9a6ef09a", "order": 3, "width": 2, "height": 1, "passthru": false, "label": "FLASH", "tooltip": "", "color": "", "bgcolor": "", "className": "", "icon": "", "payload": "flash", "payloadType": "str", "topic": "topic", "topicType": "msg", "x": 80, "y": 740, "wires": [ [ "364f12c3e131bf5a", "740a99d2.b07d1" ] ] }, { "id": "b1438827a15daca1", "type": "mqtt in", "z": "551bcfad002a399e", "name": "溫度", "topic": "ale9ufo/mqtt/temp", "qos": "1", "datatype": "auto-detect", "broker": "21957383cfd8785a", "nl": false, "rap": true, "rh": 0, "inputs": 0, "x": 70, "y": 820, "wires": [ [ "556542bd764c1eff" ] ] }, { "id": "364f12c3e131bf5a", "type": "mqtt out", "z": "551bcfad002a399e", "name": "LED", "topic": "ale9ufo/mqtt/led", "qos": "1", "retain": "true", "respTopic": "", "contentType": "", "userProps": "", "correl": "", "expiry": "", "broker": "21957383cfd8785a", "x": 250, "y": 580, "wires": [] }, { "id": "f6e68b33575b33b2", "type": "function", "z": "551bcfad002a399e", "name": "function true/false", "func": "var tmp=msg.payload;\nif (tmp=='on')\n msg.payload=true;\nif (tmp=='off')\n msg.payload=false; \nif (tmp==1)\n msg.payload=true;\nif (tmp==0)\n msg.payload=false; \nreturn msg;", "outputs": 1, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [], "x": 430, "y": 700, "wires": [ [ "ba42d4b5dbf8aef2", "941738b4b00a05de" ] ] }, { "id": "556542bd764c1eff", "type": "ui_gauge", "z": "551bcfad002a399e", "name": "", "group": "b2a47d9211a4d9b9", "order": 1, "width": 4, "height": 3, "gtype": "gage", "title": "溫度", "label": "℃", "format": "{{value}}", "min": "-40", "max": "80", "colors": [ "#00b500", "#e6e600", "#ca3838" ], "seg1": "30", "seg2": "45", "className": "", "x": 210, "y": 820, "wires": [] }, { "id": "75b4ccfded4ff808", "type": "mqtt in", "z": "551bcfad002a399e", "name": "濕度", "topic": "ale9ufo/mqtt/hum", "qos": "1", "datatype": "auto-detect", "broker": "21957383cfd8785a", "nl": false, "rap": true, "rh": 0, "inputs": 0, "x": 330, "y": 820, "wires": [ [ "711c2594688a61a9" ] ] }, { "id": "711c2594688a61a9", "type": "ui_gauge", "z": "551bcfad002a399e", "name": "", "group": "b2a47d9211a4d9b9", "order": 5, "width": 4, "height": 3, "gtype": "gage", "title": "濕度", "label": "%RH", "format": "{{value}}", "min": "5", "max": "90", "colors": [ "#00b500", "#e6e600", "#ca3838" ], "seg1": "50", "seg2": "65", "className": "", "x": 470, "y": 820, "wires": [] }, { "id": "941738b4b00a05de", "type": "debug", "z": "551bcfad002a399e", "name": "debug ", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "payload", "targetType": "msg", "statusVal": "", "statusType": "auto", "x": 530, "y": 620, "wires": [] }, { "id": "740a99d2.b07d1", "type": "function", "z": "551bcfad002a399e", "name": "startBlink", "func": "var BLINKDELAY = 250;\nvar light = true;\nvar blinker = setInterval(blink, BLINKDELAY);\nglobal.set(\"blinker\", blinker);\nfunction blink () {\n \n if (light) {\n msg.payload = 1;\n light = false;\n }\n \n else {\n msg.payload = 0;\n light = true;\n }\n \n node.send(msg);\n}\nreturn;", "outputs": 1, "timeout": "", "noerr": 0, "initialize": "", "finalize": "", "libs": [], "x": 240, "y": 740, "wires": [ [ "f6e68b33575b33b2", "32141e3321b5cef2" ] ] }, { "id": "cc1b11b1.bebb28", "type": "function", "z": "551bcfad002a399e", "name": "stopBlink", "func": "clearInterval(global.get(\"blinker\"));\nreturn msg;", "outputs": 1, "timeout": "", "noerr": 0, "initialize": "", "finalize": "", "libs": [], "x": 240, "y": 680, "wires": [ [ "f6e68b33575b33b2", "93585ef08ce182fa" ] ] }, { "id": "93585ef08ce182fa", "type": "debug", "z": "551bcfad002a399e", "name": "debug ", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "payload", "targetType": "msg", "statusVal": "", "statusType": "auto", "x": 370, "y": 640, "wires": [] }, { "id": "32141e3321b5cef2", "type": "debug", "z": "551bcfad002a399e", "name": "debug ", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "payload", "targetType": "msg", "statusVal": "", "statusType": "auto", "x": 370, "y": 760, "wires": [] }, { "id": "025f9ffb9a6ef09a", "type": "ui_group", "name": "LED", "tab": "6b8b15295653aa3c", "order": 2, "disp": true, "width": "6", "collapse": false, "className": "" }, { "id": "21957383cfd8785a", "type": "mqtt-broker", "name": "test.mosquitto.org", "broker": "test.mosquitto.org", "port": "1883", "clientid": "", "autoConnect": true, "usetls": false, "protocolVersion": "4", "keepalive": "60", "cleansession": true, "autoUnsubscribe": true, "birthTopic": "", "birthQos": "0", "birthRetain": "false", "birthPayload": "", "birthMsg": {}, "closeTopic": "", "closeQos": "0", "closeRetain": "false", "closePayload": "", "closeMsg": {}, "willTopic": "", "willQos": "0", "willRetain": "false", "willPayload": "", "willMsg": {}, "userProps": "", "sessionExpiry": "" }, { "id": "b2a47d9211a4d9b9", "type": "ui_group", "name": "DHT22", "tab": "6b8b15295653aa3c", "order": 2, "disp": true, "width": "6", "collapse": false, "className": "" }, { "id": "6b8b15295653aa3c", "type": "ui_tab", "name": "ESP32", "icon": "dashboard", "order": 7, "disabled": false, "hidden": false } ]

2025年1月16日 星期四

WOKWI ESP32 模擬 READ RFID UID (AsyncMQTT_ESP32)

 WOKWI ESP32 模擬 READ RFID UID (AsyncMQTT_ESP32)


https://wokwi.com/projects/420235174679393281







WOKWI程式
#include <WiFi.h>
extern "C" {
  #include "freertos/FreeRTOS.h"
  #include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>

//#include <MFRC522.h>
#include <Arduino.h>
//=========================
//  RFID-RC522 wire pin
//  SDA = 5   SCK =18
//  MOSI=23   MISO=19
//  RST = 4  
//  GND , VCC
//=========================
#define LEDPIN    27
#define BuzzerPIN 14

//#define MQTT_HOST     "broker.mqtt-dashboard.com"
//#define MQTT_HOST     "broker.hivemq.com"
#define MQTT_HOST       "test.mosquitto.org"  
//#define MQTT_HOST     "broker.mqttgo.io"
#define MQTT_PORT       1883

#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;


const char *SubTopic1  = "alex9ufo/esp32/led";
const char *PubTopic2  = "alex9ufo/esp32/uid";
//const char *PubTopic3  = "alex9ufo/esp32/buzzer";  
//================================================================
//================================================================
void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
//================================================================
void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}
//================================================================
void WiFiEvent(WiFiEvent_t event)
{
  switch (event)
  {
#if USING_CORE_ESP32_CORE_V200_PLUS

    case ARDUINO_EVENT_WIFI_READY:
      Serial.println("WiFi ready");
      break;

    case ARDUINO_EVENT_WIFI_STA_START:
      Serial.println("WiFi STA starting");
      break;

    case ARDUINO_EVENT_WIFI_STA_CONNECTED:
      Serial.println("WiFi STA connected");
      break;

    case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
    case ARDUINO_EVENT_WIFI_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;

    case ARDUINO_EVENT_WIFI_STA_LOST_IP:
      Serial.println("WiFi lost IP");
      break;

    case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
#else

    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;

    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
#endif

    default:
      break;
  }
}
//================================================================
void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);

  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);

  uint16_t packetIdSub1 = mqttClient.subscribe(SubTopic1 , 2);
  Serial.print("Subscribing at QoS 2, packetId: ");
  Serial.println(packetIdSub1);

  //uint16_t packetIdSub2 = mqttClient.subscribe(SubTopic2, 2);
  //Serial.print("Subscribing at QoS 2, packetId: ");
  //Serial.println(packetIdSub2);

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

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  if (WiFi.isConnected()) {
    xTimerStart(mqttReconnectTimer, 0);
  }
}
//================================================================
void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}
//================================================================
void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}
//================================================================
void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}
//================================================================
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
 
  String messageTemp;
  for (int i = 0; i < len; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }

  if (strcmp(topic, SubTopic1) == 0) {
    // If the relay is on turn it off (and vice-versa)
    Serial.println();

    Serial.println(messageTemp);  
    if (messageTemp == "on") {
      digitalWrite(LEDPIN,HIGH);
      Serial.println("LED ON");    
    }
    if (messageTemp == "off") {
      digitalWrite(LEDPIN,LOW);
      Serial.println("LED OFF");    
    }
     
  }
}
//================================================================
void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Hello, ESP32!");
  pinMode(LEDPIN, OUTPUT);
  pinMode(BuzzerPIN, OUTPUT);


  mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.onSubscribe(onMqttSubscribe);
  mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onMessage(onMqttMessage); //callback
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  // If your broker requires authentication (username and password), set them below
  //mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
  connectToWifi();
}
//================================================================
void loop() {

  if (Serial.available()) {
    Serial.println("Enter MFRC522 UID (format: XX XX XX XX):");
    String input = Serial.readStringUntil('\n');
    input.trim(); // Remove any leading or trailing whitespace
    if (isValidFormat(input)) {
      Serial.println("Valid format.");
      String temp1=input;
      uint16_t packetIdPub1 = mqttClient.publish(PubTopic2, 1, true, temp1.c_str());                            
      Serial.printf("RFID UID Number Published", PubTopic2, packetIdPub1);                            
      digitalWrite(BuzzerPIN, HIGH);
      tone(BuzzerPIN, 750);
      delay(1000);
      digitalWrite(BuzzerPIN, LOW);
      noTone(BuzzerPIN);

    } else {
      Serial.println("Invalid format. Enter Enter MFRC522 UID (format: XX XX XX XX):");
    }
  }
}
//================================================================
bool isValidFormat(String input) {
  // Check if the input matches the format "XX XX XX XX"
  if (input.length() == 11 && input.charAt(2) == ' ' && input.charAt(5) == ' ' && input.charAt(8) == ' ') {
    for (int i = 0; i < input.length(); i++) {
      if (i != 2 && i != 5 && i != 8) {
        if (!isDigit(input.charAt(i))) {
          return false;
        }
      }
    }
    return true;
  }
  return false;
}
//================================================================


rfid-rc522.chip.c程式

#include "wokwi-api.h"
#include <stdint.h>
#include <stdio.h>
#include <unistd.h> // For sleep function

// Function to simulate SPI communication
void spi_transfer(uint8_t *data_out, uint8_t *data_in, uint8_t len) {
    // Simulate SPI transfer
    printf("MFRC522: Sending data: ");
    for (int i = 0; i < len; i++) {
        printf("0x%02X ", data_out[i]);
    }
    printf("\n");

    // Simulate receiving data
    for (int i = 0; i < len; i++) {
        data_in[i] = 0xAB; // Dummy data
    }
    printf("MFRC522: Received data: ");
    for (int i = 0; i < len; i++) {
        printf("0x%02X ", data_in[i]);
    }
    printf("\n");
}

// Function to send UID data to Arduino
void send_uid_to_arduino() {
    // Loop for sending 10 sets of UID data
    for (int i = 0; i < 10; i++) {
        // Simulate UID data
        uint8_t uid_data[4] = {0x12, 0x34, 0x56, 0x78};

        // Print UID data
        printf("UID %d: ", i + 1);
        for (int j = 0; j < 4; j++) {
            printf("%02X ", uid_data[j]);
        }
        printf("\n");

        // Send UID data to Arduino via SPI
        spi_transfer(uid_data, NULL, 4);

        // Wait for 1 second (for demonstration, reduce to 1 second)
        sleep(1);
    }
}


// Function to initialize the chip and SPI pins
void chip_init() {
    // Initialize MFRC522
    // Reset MFRC522
    // Additional initialization steps can be added here
     //mfrc522_write(0x0A, 0x0F); // Command register address and reset command
     
}

int main() {
    // Initialize chip
    chip_init();

    // Send UID data to Arduino
    // Send UID data to Arduino every 10 seconds
    while (1) {
        send_uid_to_arduino();
        // Wait for 10 seconds
        sleep(10);
    }

    return 0;
}

rfid-rc522.chip.json程式
{
  "name": "RFID-RC522",
  "author": "arducoding",
  "pins": [
    "SDA",
    "SCK",
    "MOSI",
    "MISO",
    "RST",
    "GND",
    "VCC",
    "",
    "",
    "",
    "",
    "",
    ""
  ],
  "controls": []
}

2025年1月14日 星期二

ESP32 DHT22 (Blynk)

 ESP32 DHT22 (Blynk)










































WOKWI程式


#define BLYNK_PRINT Serial

#define BLYNK_TEMPLATE_ID "TMPL6BrcHyG1i"
#define BLYNK_TEMPLATE_NAME "DHT22"
#define BLYNK_AUTH_TOKEN "ZHp5tlWYKk0Txynw5besSRULNcjT9UmE"

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
#define LED 12

DHTesp dhtSensor;

int temp;
int humi;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

BlynkTimer timer;

// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void myTimerEvent()
{
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  temp=data.temperature;
  humi=data.humidity;
  Blynk.virtualWrite(V0, temp);
  Blynk.virtualWrite(V1, humi);

  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");
 
}
BLYNK_WRITE(V2)
{
  int pinValue = param.asInt();
  Serial.print("V2 Switch value is: ");
  Serial.println(pinValue);

  if(pinValue == 1){
    digitalWrite(LED,HIGH);
    Serial.println("Led 亮");  
  }
  else{
    digitalWrite(LED,LOW);
    Serial.println("Led 滅");
  }
}
void setup() {
  Serial.begin(115200);

  pinMode(LED, OUTPUT);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
  timer.setInterval(1000L, myTimerEvent);

}

void loop() {
 
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
 
}

作業2 MQTT (Relay + DHT22) 控制 ------- 利用Node-Red

作業2 MQTT (Relay + DHT22) 控制 ------- 利用Node-Red 1) 安裝Node-Red  https://ithelp.ithome.com.tw/articles/10201795 https://www.youtube.com/watch?v...