ESP32 MQTT – Publish DS18B20 Temperature Readings
WOKWI程式
#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#define WLAN_SSID "Wokwi-GUEST"
#define WLAN_PASS ""
/************************* Adafruit.io Setup ***************************/
#define AIO_SERVER "broker.hivemq.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME ""
#define AIO_KEY ""
#define AIO_FEED_1 "alex9ufo/esp32/ds18b20/temperature"
// Raspberry Pi Mosquitto MQTT Broker
//#define MQTT_HOST IPAddress(192, 168, 1, XXX)
// For a cloud MQTT broker, type the domain name
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_USERNAME, AIO_KEY);
/****************************** Feeds ***************************************/
// Setup feeds 'temp' and 'hmdt' for publishing.
Adafruit_MQTT_Publish tempPub = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME AIO_FEED_1);
// Setup a feed called 'onoff' for subscribing to changes to the ON/OFF button
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
// Temperature value
float temp;
unsigned long lastMsg = 0;
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 10 seconds...");
mqtt.disconnect();
delay(10000); // wait 10 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
void setup() {
// Start the DS18B20 sensor
sensors.begin();
Serial.begin(115200);
Serial.println();
Serial.println();
// Connect to WiFi access point.
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(); Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
}
void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
MQTT_connect();
// this is our 'wait for incoming subscription packets and callback em' busy subloop
// try to spend your time here:
mqtt.processPackets(10000);
// ping the server to keep the mqtt connection alive
// NOT required if you are publishing once every KEEPALIVE seconds
if(! mqtt.ping()) {
mqtt.disconnect();
}
// Publish feeds
unsigned long now = millis();
if (now - lastMsg > 10000) {
lastMsg = now;
// New temperature readings
sensors.requestTemperatures();
// Temperature in Celsius degrees
temp = sensors.getTempCByIndex(0);
// Temperature in Fahrenheit degrees
//temp = sensors.getTempFByIndex(0);
Serial.println("Temperature: " +String(temp) + "°C");
Serial.println("---");
char strTemperature[20];
sprintf(strTemperature, "%.1f", temp);
tempPub.publish(strTemperature);
}
}
Node-Red程式
[
{
"id": "9a55977d9dd88494",
"type": "mqtt in",
"z": "72c4df790a4c757f",
"name": "",
"topic": "alex9ufo/esp32/ds18b20/temperature",
"qos": "2",
"datatype": "auto-detect",
"broker": "2380dcc0d36d2c6a",
"nl": false,
"rap": true,
"rh": 0,
"inputs": 0,
"x": 610,
"y": 240,
"wires": [
[
"ea3b6b36bf2cac5b"
]
]
},
{
"id": "ea3b6b36bf2cac5b",
"type": "ui_gauge",
"z": "72c4df790a4c757f",
"name": "",
"group": "4f4d1221d5fcd2d2",
"order": 0,
"width": 0,
"height": 0,
"gtype": "gage",
"title": "gauge",
"label": "°C",
"format": "{{value}}",
"min": "-55",
"max": "125",
"colors": [
"#00b500",
"#e6e600",
"#ca3838"
],
"seg1": "25",
"seg2": "50",
"className": "",
"x": 870,
"y": 240,
"wires": []
},
{
"id": "2380dcc0d36d2c6a",
"type": "mqtt-broker",
"name": "",
"broker": "broker.hivemq.com",
"port": "1883",
"clientid": "",
"autoConnect": true,
"usetls": false,
"protocolVersion": "4",
"keepalive": "60",
"cleansession": true,
"birthTopic": "",
"birthQos": "0",
"birthPayload": "",
"birthMsg": {},
"closeTopic": "",
"closeQos": "0",
"closePayload": "",
"closeMsg": {},
"willTopic": "",
"willQos": "0",
"willPayload": "",
"willMsg": {},
"userProps": "",
"sessionExpiry": ""
},
{
"id": "4f4d1221d5fcd2d2",
"type": "ui_group",
"name": "溫度",
"tab": "096dc3f20d4aa28b",
"order": 1,
"disp": true,
"width": "6",
"collapse": false,
"className": ""
},
{
"id": "096dc3f20d4aa28b",
"type": "ui_tab",
"name": "MQTT DS18B20",
"icon": "dashboard",
"order": 128,
"disabled": false,
"hidden": false
}
]
沒有留言:
張貼留言