使用Node-RED控制LED&風扇-ESP32
使用Node-RED控制LED&風扇-ESP32
原本這個實作主題是搭配夜市小霸王-尤老師的課程,使用LineBot語音控制LED和風扇,
但因為正好有事,提前請了假,所以就先把手邊拿到的零件先做看看。
一方面也學習一下CSS按鍵的制作。
接線圖
正負端就都接在板子上的Vcc和GND,
風扇控制線接IO35
LED控制線接IO34
ESP32上的程式碼
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
const int ledR=15;
const int ledG=2;
const int ledB=4;
const int LIGHT=2;
const int Fan=18;
const char* ssid="---";
const char* password="-----";
const char* mqtt_server="192.168.---.---";
//如果連線至MQTT成功,即會開始接收訂閱的主題
void reconnect(){
while (! client.connected()){
Serial.print("Attempting MQTT connection...");
if (client.connect("esp32Client")){
Serial.println("connected");
client.subscribe("linebot/onoff"); //LED訂閱主題
client.subscribe("fan_out/onoff"); //風扇訂閱主題
}else {
Serial.print("failed connected is : ");
Serial.println(client.state());
delay(2000);
}
}
}
//當訂閱成功後,callback開始監聽broker的發送主題的訊息
void callback(char *topic, byte *message, unsigned int length){
String msgList;
Serial.print("topic:");
Serial.println(topic);
for (int i=0; i<length; i++){
Serial.print(char(message[i]));
msgList+=char(message[i]);
}
Serial.println();
//依收到的訊息來做相應的收受端動作
if (String(topic)=="linebot/onoff"){
if (msgList=="1"){
Serial.println("on");
digitalWrite(LIGHT, HIGH);
}else if (msgList=="0"){
Serial.println("off");
digitalWrite(LIGHT, LOW);
}
}
if (String(topic)=="fan_out/onoff"){
if (msgList=="a"){
Serial.println("fan_on");
digitalWrite(Fan, HIGH);
}else if (msgList=="b"){
Serial.println("fan_off");
digitalWrite(Fan, LOW);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(ledR, OUTPUT);
pinMode(ledG, OUTPUT);
pinMode(ledB, OUTPUT);
pinMode(LIGHT, OUTPUT);
pinMode(Fan, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
delay(50);
Serial.print(".");
}
Serial.println("connected successful");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (! client.connected()){
reconnect();
}
client.loop();
}
Node-RED節點配置
<style id="dashboard-style-override">
/*icon size for buttons*/
.nr-dashboard-button .md-button i {
font-size: 60px;
text-shadow:
-1px -1px 1px #444444,
1px -1px 1px #444444,
-1px 1px 1px #444444,
1px 1px 1px #444444,
0px 0px 10px #888888;
}
/* round button */
.nr-dashboard-button .md-button {
border-radius:50%;
border-style:solid;
border-width: 3px;
border-color: #888888;
left: 25px;
}
</style>
留言
張貼留言