2019年11月2日 星期六

Control ESP32 LED Blynk Thru MQTT



Control ESP32 LED by Blynk Thru MQTT 


















/*
 *  Receive data Vo , V1 ,V2 Form Blynk , Processed & Publish to MQTT (broker.mqtt-dashboard.com)
 *  Subscribe MQTT LED status on,off,flash data , Processed to NodeMcu WEMOS D1 LED
 *
 */

//=====Blynk=================================
#define BLYNK_PRINT Serial
//#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>   //including the library of SimpleTimer
//=====ESP32=================================
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>

//=====NodeMCU =================================
//#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Define NodeMCU D3 pin to as temperature data pin of  DHT11

//========================LED====================
//#define LED     D0        // Led in NodeMCU at pin GPIO16 (D0).
#define LED     2       // Led in ESP32 at pin 2.
#define REST    1000    //Rest Between Inhalations.
//========================LED====================

// Update these with values suitable for your network.
//const char* ssid = "******";//put your own wifi ssid here
//const char* password = "******";// put your wifi password here

//const char* ssid = "My ASUS";//put your wifi ssid here
//const char* password = "alex9981" ;//put your wifi password here
const char* ssid = "PTS-2F";//put your wifi ssid here
const char* password = "PTS6662594" ;//put your wifi password here 

//const char* ssid2 = "74170287";//put your wifi ssid here
//const char* password2 = "24063173" ;//put your wifi password here
const char* ssid2 = "PTS-2F";//put your wifi ssid here
const char* password2 = "PTS6662594" ;//put your wifi password here 

//========================================================
SimpleTimer timer;
//char auth[] = "Your Auth. Key";            // You should get Auth Token in the Blynk App.
                                           // Go to the Project Settings (nut icon).
const char auth[] = "KIdOF5-sSBiArcujH9UDoMPM6vH08iBH";
//========================================================

const char* mqtt_server = "broker.mqtt-dashboard.com";
//const char* mqtt_server = "iot.eclipse.org";
//========================================================
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
bool Flash = false;  //true
//========================================================
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  BLYNK_WRITE(V0)
  {
    //int pinValue = param.asInt(); // assigning incoming value from pin V0 to a variable
    // You can also use:
    String i = param.asStr();
    // double d = param.asDouble();
    Serial.print("V0 value is: ");
    Serial.println(i);
    Flash = false;
    Blynk.virtualWrite(V3,"OFF");
    client.publish("alex9ufo/outTopic/ESP32LED","#off");
 
  }

  BLYNK_WRITE(V1)
  {
    //int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable
    // You can also use:
    String i = param.asStr();
    // double d = param.asDouble();
    Serial.print("V1 value is: ");
    Serial.println(i);
    Flash = false;
    Blynk.virtualWrite(V3,"ON");
    client.publish("alex9ufo/outTopic/ESP32LED","#on");
 }
  BLYNK_WRITE(V2)
  {
    //int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable
    // You can also use:
    String i = param.asStr();
    // double d = param.asDouble();
    Serial.print("V2 value is: ");
    Serial.println(i);
    //Flash = false;
    Blynk.virtualWrite(V3,"Flash");
    client.publish("alex9ufo/outTopic/ESP32LED","#flash");
  }


//========================================================
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());
  Serial.println("MQTT-NodeMcu-LED Control.");
  //timer.setInterval(1000L, myTimerEvent);

}
//========================================================
void callback(char* topic, byte* payload, unsigned int length)    // call back "Alex9ufo-DHT3-Command"
{
  char* message = (char *) payload;
  message[length] = 0;
  //String message;
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.println(message);
  String message1;
  for (int i = 0; i < length; i++) {
    message1 = message1 + (char)payload[i];  //Conver *byte to String
  }
  //Serial.print(message);
  if(message1 == "#on")
  {
      digitalWrite(BUILTIN_LED,HIGH);
      Flash = false;
  }   //LED on
  if(message1 == "#off")
  {
    digitalWrite(BUILTIN_LED,LOW);
    Flash = false;
  } //LED off
  if(message1== "#flash") {
     Flash = true;
     digitalWrite(BUILTIN_LED, HIGH);
   } // if(message== "#flashLED")


} //end callback
//========================================================
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "NodeMcu-ESP8266Client-";
    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/outTopic/ESP32LED");
    } 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() {
  pinMode(LED, OUTPUT);   // LED pin as output.
  //========MQTT==============
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //========Blynk==============
  Blynk.begin(auth, ssid2, password2);

}
//========================================================
void loop() {
  if (Flash)
  {
    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
    delay(500);
  }
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  // read  sensor every 6 seconds
  if (now - lastMsg > 6000) {
     lastMsg = now;
     String msg="";
     char message[58];
     msg= msg+ "#on";
     msg.toCharArray(message,58); 
     client.publish("Alex9ufo-MQTT-LED",message);
  }
    //=========Blynk======================
    Blynk.run();
}
//========================================================



















沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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