MQTT-Nord-RED顯示超音波測距數據+控制LED
MQTT-Nord-RED顯示超音波測距數據+控制LED
超音波模組(HC-SC04)測試回顧-點我回顧
MQTT相關布暑-點我回顧
#include <Ultrasonic.h>
#include <WiFi.h>
#include <PubSubClient.h>
Ultrasonic ultrasonic(32, 33);
const char* ssid = "---";
const char* password = "-----";
const char* mqttServer = "192.168.67.22";
//wifi客戶端及MQTT客戶端代數
WiFiClient espClient;
PubSubClient client(espClient);
//設定wifi
void wifiConn(){
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(50);
}
Serial.println("Connected successful!");
Serial.println(WiFi.localIP());
}
//檢查訂閱的字串是否含有on和off,如果比對下來是
//nord-red裡的標頭一樣,而且包含on就開燈,off就關燈
void callback(char *topic, byte *message, unsigned int length){
String messageDist;
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
for (int i = 0; i < length; i++)
{
Serial.print(char(message[i]));
messageDist += char(message[i]);
}
Serial.println();
if (String(topic) == "esp32/output"){
if (messageDist == "on"){
Serial.print("on");
digitalWrite(LED_BUILTIN, HIGH);
}else if (messageDist == "off"){
Serial.print("off");
digitalWrite(LED_BUILTIN, LOW);
}
}
}
//萬一連不上mqtt就重新連線
void reconnect(){
while (! client.connected()){
Serial.print("Attempting MQTT connection...");
if (client.connect("esp32Client")){
Serial.println("connected");
client.subscribe("esp32/output");
}else {
Serial.print("failed connected is : ");
Serial.println(client.state());
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
wifiConn();
client.setServer(mqttServer, 1883);
client.setCallback(callback);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if (! client.connected()){
reconnect();
}
client.loop();
long lastTime = 0;
long currentTime = millis();
float distance = 0;
if (currentTime - lastTime > 3000){
lastTime = currentTime;
distance = ultrasonic.read(CM);
Serial.println(distance);
char distStr[8] = "";
dtostrf(distance, 1, 2, distStr);
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("CM");
client.publish("esp32/distanceRead", distStr);
delay(500);
}
}
留言
張貼留言