Skip to content

Instantly share code, notes, and snippets.

@aeshirey
Last active July 16, 2019 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeshirey/c9e82b5dcb004cf976a6f6c5694a2788 to your computer and use it in GitHub Desktop.
Save aeshirey/c9e82b5dcb004cf976a6f6c5694a2788 to your computer and use it in GitHub Desktop.
#include <DHTesp.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <ESP8266WiFi.h>
#define LOOP_MS 60000
#define DhtPin 14
DHTesp dht;
#define ssid "my_network"
#define pwd "my_password"
WiFiClient client;
#define MQTT_SERVER "my mqtt broker"
#define MQTT_TOPIC "my mqtt topic"
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, 1883, "", "");
Adafruit_MQTT_Publish pub = Adafruit_MQTT_Publish(&mqtt, MQTT_TOPIC);
// convert celcius to fahrenheit
inline float c_to_f(float c) { return 1.8 * c + 32; }
void MQTT_connect() {
if (mqtt.connected())
return;
const uint8_t retries = 3;
int8_t ret;
for (int i = 0; i < retries; i++) {
if ((ret = mqtt.connect()) == 0)
return;
delay(5000);
}
while(1); // couldn't connect. die and wait for WDT to reset
}
void setup() {
dht.setup(DhtPin, DHTesp::DHT11);
WiFi.begin(ssid, pwd);
while (WiFi.status() != WL_CONNECTED)
delay(500);
}
void loop() {
MQTT_connect();
TempAndHumidity lastValues = dht.getTempAndHumidity();
pub.publish(c_to_f(lastValues.temperature));
delay(LOOP_MS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment