2025年2月1日 星期六

MQTT to Ws2812b 主燈整合按鈕

 MQTT to Ws2812b 主燈整合按鈕










char* MQTTServer = "mqttgo.io";//免註冊MQTT伺服器
int MQTTPort = 1883;//MQTT Port 除非加密,否則不用更改port
char* MQTTUser = "";//不須帳密
char* MQTTPassword = "";//不須帳密

//訂閱主題1:改變LED燈號(記得改Topic)
char* MQTTSubTopic1 = "alex9ufo/led/power";
char* MQTTSubTopic2 = "alex9ufo/led/color";

function color

var temp1=flow.get('color1');
var temp2=flow.get('color2');
var temp3=flow.get('color3');

if (temp1<10){
    temp1='00'+temp1;
}

if (temp2<10){
    temp2='00'+temp2;
}
if (temp3<10){
    temp3='00'+temp3;
}

if (temp1>10 && temp1<100){
    temp1='0'+temp1;
}

if (temp2>10 && temp2<100){
    temp2='0'+temp2;
}

if (temp3>10 && temp3<100){
    temp3='0'+temp3;
}

msg.payload=temp1+','+temp2+','+temp3;            
return msg;



Wokwi程式
//控制燈號顏色

#include <WiFi.h>
#include <PubSubClient.h> //請先安裝PubSubClient程式庫

// ------ws2812b ------

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif
#define PIN        2   //接腳
#define NUMPIXELS 16   //燈數量
#define ttb223_pin 12
bool ws2812b_mainled=false;
// ------ 以下修改成你自己的WiFi帳號密碼 ------
const int Led = 14;

char* ssid = "Wokwi-GUEST"; //請修改為您連線的網路名稱
char* password = ""; //請修改為您連線的網路密碼
// ------ 以下修改成你MQTT設定 ------
char* MQTTServer = "mqttgo.io";//免註冊MQTT伺服器
int MQTTPort = 1883;//MQTT Port 除非加密,否則不用更改port
char* MQTTUser = "";//不須帳密
char* MQTTPassword = "";//不須帳密

//訂閱主題1:改變LED燈號(記得改Topic)
char* MQTTSubTopic1 = "alex9ufo/led/power";
char* MQTTSubTopic2 = "alex9ufo/led/color";
//建立MQTT與聯網物件
WiFiClient WifiClient;
PubSubClient MQTTClient(WifiClient);

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
#define DELAYVAL 500
int r=150,g=150,b=150;
bool lighton=false;
//=============================================
void setup() {
  Serial.begin(115200);
  pinMode(Led, OUTPUT);

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

  #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
  #endif
  pixels.begin();
  pinMode(ttb223_pin, INPUT);
}
//=============================================
void loop() {
  //如果WiFi連線中斷,則重啟WiFi連線
  if (WiFi.status() != WL_CONNECTED) { WifiConnecte(); }

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

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

  if(digitalRead(ttb223_pin))
  {
    ws2812b_mainled=!ws2812b_mainled;
    //Serial.print("當下狀態:");
    //Serial.println(ws2812b_mainled);
    while(digitalRead(ttb223_pin)){
      delay(50);
    }
  }  
 
  if(ws2812b_mainled)
  {
      //Serial.print("開啟燈號");
      digitalWrite(Led,HIGH);
      lighton=true;
      //pixels.clear();
      for (int i=0;i<NUMPIXELS;i++){
        pixels.setPixelColor(i, pixels.Color(r, g, b));
      }
      pixels.show();
  }
  else{
      //Serial.print("關閉燈號");
      //pixels.clear();
      digitalWrite(Led,LOW);
      lighton=false;
      for (int i=0;i<NUMPIXELS;i++){
        pixels.setPixelColor(i, pixels.Color(0, 0, 0));
      }
      pixels.show();
  }
}

//=============================================

//開始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);
  //以下開始處理訂閱主題
  MQTTClient.setCallback(MQTTCallback); //收到訂閱資料時,要處理MQTTCALLBACK
  while (!MQTTClient.connected()) {
    //以亂數為ClietID
    String  MQTTClientid = "esp32-" + String(random(1000000, 9999999));//建立一個郵差,為了要不一樣,所以使用亂數
    if (MQTTClient.connect(MQTTClientid.c_str(), MQTTUser, MQTTPassword)) {
      //連結成功,顯示「已連線」。
      Serial.println("MQTT已連線");
      //訂閱SubTopic1主題
      MQTTClient.subscribe(MQTTSubTopic1);
      MQTTClient.subscribe(MQTTSubTopic2);
    } else {
      //若連線不成功,則顯示錯誤訊息,並重新連線
      Serial.print("MQTT連線失敗,狀態碼=");
      Serial.println(MQTTClient.state());
      Serial.println("五秒後重新連線");
      delay(5000);
    }
  }
}
//=============================================
//接收到訂閱時
void MQTTCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print(topic); Serial.print("訂閱通知:");
  String payloadString;//將接收的payload轉成字串
  //顯示訂閱內容
  for (int i = 0; i < length; i++) {
    payloadString = payloadString + (char)payload[i];
  }
  Serial.println(payloadString);
  //比對主題是否為訂閱主題1,若相同則執行動作的部分,需要注意payloadString內容的資料是否與app內的訊息相同。
  if (strcmp(topic, MQTTSubTopic1) == 0) {
    Serial.println("改變燈號:" + payloadString);
    if (payloadString == "on") {
      Serial.println("開啟燈號:");
      Serial.print("r=");Serial.println(r);
      Serial.print("g=");Serial.println(g);
      Serial.print("b=");Serial.println(b);

      ws2812b_mainled=true;
      lighton=true;
      digitalWrite(Led,HIGH);
      //pixels.clear();
      for (int i=0;i<NUMPIXELS;i++){
        pixels.setPixelColor(i, pixels.Color(r, g, b));
      }
      pixels.show();
    }


    if (payloadString == "off") {
      Serial.print("關閉燈號");
      lighton=false;
      ws2812b_mainled=false;
 
      digitalWrite(Led,LOW);
      //pixels.clear();
      for (int i=0;i<NUMPIXELS;i++){
        pixels.setPixelColor(i, pixels.Color(0, 0, 0));
      }
      pixels.show();
    }
  }

  if (strcmp(topic, MQTTSubTopic2) == 0) {
    r=payloadString.substring(0,3).toInt();
    g=payloadString.substring(4,7).toInt();
    b=payloadString.substring(8,11).toInt();

    Serial.print("r=");Serial.println(r);
    Serial.print("g=");Serial.println(g);
    Serial.print("b=");Serial.println(b);
    if (lighton){
      for (int i = 0; i < NUMPIXELS; i++) {
        pixels.setPixelColor(i, pixels.Color(r, g, b));
      }
      pixels.show();
    }

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



Node-Red程式

[ { "id": "3e2979e64af0e8a2", "type": "ui_button", "z": "d138672bfb536fe9", "name": "", "group": "dc7f044bc6789b40", "order": 1, "width": 0, "height": 0, "passthru": false, "label": "on", "tooltip": "", "color": "", "bgcolor": "", "className": "", "icon": "", "payload": "on", "payloadType": "str", "topic": "topic", "topicType": "msg", "x": 130, "y": 100, "wires": [ [ "cd6ddbf34532cf3c" ] ] }, { "id": "50c12cd0e81ccebb", "type": "ui_button", "z": "d138672bfb536fe9", "name": "", "group": "dc7f044bc6789b40", "order": 2, "width": 0, "height": 0, "passthru": false, "label": "off", "tooltip": "", "color": "", "bgcolor": "", "className": "", "icon": "", "payload": "off", "payloadType": "str", "topic": "topic", "topicType": "msg", "x": 130, "y": 140, "wires": [ [ "cd6ddbf34532cf3c" ] ] }, { "id": "da9e59b25648d165", "type": "ui_slider", "z": "d138672bfb536fe9", "name": "", "label": "R Color", "tooltip": "", "group": "dc7f044bc6789b40", "order": 3, "width": 0, "height": 0, "passthru": true, "outs": "end", "topic": "topic", "topicType": "msg", "min": 0, "max": "255", "step": "5", "className": "", "x": 140, "y": 220, "wires": [ [ "ef45b4d0013999df" ] ] }, { "id": "73f6c496602dd4f8", "type": "ui_slider", "z": "d138672bfb536fe9", "name": "", "label": "G Color", "tooltip": "", "group": "dc7f044bc6789b40", "order": 4, "width": 0, "height": 0, "passthru": true, "outs": "end", "topic": "topic", "topicType": "msg", "min": 0, "max": "255", "step": "5", "className": "", "x": 140, "y": 260, "wires": [ [ "5609ceb0fdf6e07b" ] ] }, { "id": "5cdc801a07a5f9c5", "type": "ui_slider", "z": "d138672bfb536fe9", "name": "", "label": "B Color", "tooltip": "", "group": "dc7f044bc6789b40", "order": 5, "width": 0, "height": 0, "passthru": true, "outs": "end", "topic": "topic", "topicType": "msg", "min": 0, "max": "255", "step": "5", "className": "", "x": 140, "y": 300, "wires": [ [ "44fba2858ee96864" ] ] }, { "id": "ef45b4d0013999df", "type": "function", "z": "d138672bfb536fe9", "name": "function color R", "func": "var temp=msg.payload;\nflow.set('color1',temp);\nreturn msg;", "outputs": 1, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [], "x": 300, "y": 220, "wires": [ [ "fc3d21f2a7b4ca94", "779030dec6b01b39" ] ] }, { "id": "5609ceb0fdf6e07b", "type": "function", "z": "d138672bfb536fe9", "name": "function color G", "func": "var temp=msg.payload;\nflow.set('color2',temp);\nreturn msg;\n", "outputs": 1, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [], "x": 300, "y": 260, "wires": [ [ "fc3d21f2a7b4ca94" ] ] }, { "id": "44fba2858ee96864", "type": "function", "z": "d138672bfb536fe9", "name": "function color B", "func": "var temp = msg.payload;\nflow.set('color3', temp);\nreturn msg;", "outputs": 1, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [], "x": 300, "y": 300, "wires": [ [ "fc3d21f2a7b4ca94" ] ] }, { "id": "fc3d21f2a7b4ca94", "type": "function", "z": "d138672bfb536fe9", "name": "function color", "func": "var temp1=flow.get('color1');\nvar temp2=flow.get('color2');\nvar temp3=flow.get('color3');\n\nif (temp1<10){\n temp1='00'+temp1;\n}\n\nif (temp2<10){\n temp2='00'+temp2;\n} \nif (temp3<10){\n temp3='00'+temp3;\n}\n\nif (temp1>10 && temp1<100){\n temp1='0'+temp1;\n}\n\nif (temp2>10 && temp2<100){\n temp2='0'+temp2;\n}\n\nif (temp3>10 && temp3<100){\n temp3='0'+temp3;\n}\n\nmsg.payload=temp1+','+temp2+','+temp3; \nreturn msg;", "outputs": 1, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [], "x": 490, "y": 260, "wires": [ [ "da38bb5eb4a4cd45" ] ] }, { "id": "da38bb5eb4a4cd45", "type": "mqtt out", "z": "d138672bfb536fe9", "name": "COLOR", "topic": "alex9ufo/led/color", "qos": "1", "retain": "true", "respTopic": "", "contentType": "", "userProps": "", "correl": "", "expiry": "", "broker": "70940176.2b2d3", "x": 640, "y": 260, "wires": [] }, { "id": "cd6ddbf34532cf3c", "type": "mqtt out", "z": "d138672bfb536fe9", "name": "POWER ON&OFF", "topic": "alex9ufo/led/power", "qos": "1", "retain": "true", "respTopic": "", "contentType": "", "userProps": "", "correl": "", "expiry": "", "broker": "70940176.2b2d3", "x": 330, "y": 120, "wires": [] }, { "id": "2a18806e09a7dab2", "type": "comment", "z": "d138672bfb536fe9", "name": "", "info": "//訂閱主題1:改變LED燈號(記得改Topic)\nchar* MQTTSubTopic1 = \"alex9ufo/led/power\";\nchar* MQTTSubTopic2 = \"alex9ufo/led/color\";", "x": 130, "y": 40, "wires": [] }, { "id": "779030dec6b01b39", "type": "debug", "z": "d138672bfb536fe9", "name": "debug 346", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "false", "statusVal": "", "statusType": "auto", "x": 510, "y": 200, "wires": [] }, { "id": "dc7f044bc6789b40", "type": "ui_group", "name": "POWER&COLOR", "tab": "8990f08c70bfb060", "order": 1, "disp": true, "width": "6", "collapse": false, "className": "" }, { "id": "70940176.2b2d3", "type": "mqtt-broker", "name": "", "broker": "broker.mqttgo.io", "port": "1883", "clientid": "", "autoConnect": true, "usetls": false, "protocolVersion": "4", "keepalive": "15", "cleansession": true, "birthTopic": "", "birthQos": "0", "birthPayload": "", "birthMsg": {}, "closeTopic": "", "closePayload": "", "closeMsg": {}, "willTopic": "", "willQos": "0", "willPayload": "", "willMsg": {}, "sessionExpiry": "" }, { "id": "8990f08c70bfb060", "type": "ui_tab", "name": "WS2812B", "icon": "dashboard", "order": 7, "disabled": false, "hidden": false } ]

沒有留言:

張貼留言

作業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...