Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- #include <OneWire.h>
- #include <DallasTemperature.h>
- #define DEBUG false
- #define PUBLISH_RATE 3600
- #define DEEP_SLEEP true
- #define MQTT_TOPIC "home/outdoor/temperature"
- #define ONE_WIRE_BUS 2
- #ifdef DEBUG
- #define DEBUG_PRINT(x) Serial.println (x)
- #else
- #define DEBUG_PRINT(x)
- #endif
- const char* ssid = "XXXX";
- const char* password = "XXXXX";
- const char *mqtt_server = "XXXXXX";
- const int mqtt_port = 18967;
- const char *mqtt_user = "XXXX";
- const char *mqtt_pass = "XXXXX";
- const char *mqtt_client_name = "esp8266-outdoor-temperature";
- OneWire oneWire(ONE_WIRE_BUS);
- DallasTemperature sensors(&oneWire);
- WiFiClient espClient;
- PubSubClient client(espClient);
- void setup() {
- if (DEBUG) Serial.begin(115200);
- setup_wifi();
- client.setServer(mqtt_server, mqtt_port);
- sensors.begin();
- }
- void setup_wifi() {
- delay(10);
- DEBUG_PRINT(ssid);
- WiFi.begin(ssid, password);
- WiFi.mode(WIFI_STA);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- DEBUG_PRINT(WiFi.localIP());
- }
- void reconnect() {
- // Loop until we're reconnected
- while (!client.connected()) {
- DEBUG_PRINT("Attempting MQTT connection...");
- if (client.connect(mqtt_client_name, mqtt_user, mqtt_pass)) {
- DEBUG_PRINT("connected");
- } else {
- Serial.println(" try again in 5 seconds");
- delay(5000);
- }
- }
- }
- void loop() {
- if (!client.connected()) {
- reconnect();
- }
- client.loop();
- sensors.requestTemperatures();
- float number = sensors.getTempCByIndex(0);
- String payload = "{";
- payload += "\"temperature\":";
- payload += number;
- payload += "}";
- DEBUG_PRINT(payload);
- client.publish(MQTT_TOPIC, (char*) payload.c_str());
- delay(5000);
- if (DEEP_SLEEP) {
- DEBUG_PRINT("Deep Sleep");
- ESP.deepSleep(PUBLISH_RATE * 1e6);
- } else {
- delay(PUBLISH_RATE * 1e3);
- }
- }
Add Comment
Please, Sign In to add comment