-->
Page 1 of 3

MQTT and dht11

PostPosted: Sun Mar 29, 2015 2:37 am
by claudiuchiru
simple example



#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <DHT.h>

const char* ssid = "ssid";
const char* password = "password";
char* topic = "dht11";
char* server = "mqtt broker adress";
String clientName = "Arduino-esp";

#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE,15);

WiFiClient wifiClient;
PubSubClient client(server, 1883, callback, wifiClient);

void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}

void setup() {
Serial.begin(115200);
delay(10);
dht.begin();
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

Serial.print("Connecting to ");
Serial.print(server);
Serial.print(" as ");
Serial.println(clientName);


if (client.connect((char*) clientName.c_str())) {
Serial.println("Connected to MQTT broker");
Serial.print("Topic is: ");
Serial.println(topic);

}
else {
Serial.println("MQTT connect failed");
Serial.println("Will reset and try again...");
abort();
}
}

void loop() {

float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}


static int counter = 0;
String payload ;
payload += t;
payload += ":";
payload += h;

if (client.connected()){
Serial.print("Sending payload: ");
Serial.println(payload);

if (client.publish(topic, (char*) payload.c_str()))
{
Serial.println("Publish ok");
}
else {
Serial.println("Publish failed");
}

}
else {
if (client.connect((char*) clientName.c_str())) {
Serial.println("Connected to MQTT broker");
Serial.print("Topic is: ");
Serial.println(topic);
}
}
++counter;
delay(5000);
}

Re: MQTT and dht11

PostPosted: Mon Mar 30, 2015 2:19 pm
by Mikejstb
a dumb question - where do I get dht11.h?

Re: MQTT and dht11

PostPosted: Mon Mar 30, 2015 2:25 pm
by igrr
You need to get this library:
https://github.com/adafruit/DHT-sensor-library
Note that it's DHT.h not DHT11.h :)

Re: MQTT and dht11

PostPosted: Mon Mar 30, 2015 2:35 pm
by Mikejstb
got it - thanks so much!