Uploading DHT-11 Temperature & Humidity Data using MQTT
Refer to Log Data Upload - Humidity & Temperature Web Logger posting for more information about Arduino & DHT-11.
Download MQTT Publisher Library for Arduino
If you need document... http://knolleary.net/arduino-client-for-mqtt/
Choose MQTT Broker
There are several public MQTT brokers; however, we are going to use HTML/JS to see Temperature & Humidity Data thus we need to use WebSocket.
I am going to use broker.mqttdashboard.com because it supports WebSocket.
IP is 212.72.74.21
Other good Brokers:
- m2m.eclipse.org (IP: 198.41.30.241)
- test.mosquitto.org (IP: 85.119.83.194)
If you want your own Broker, use Mosquitto.
Install and run mosquitto.exe.
TOPIC NAME
broker.mqttdashboard.com only supports 1 sub-tree, which means that it is possible to use "DHT11/temphum" as TOPIC, but "DHT11/temphum/room" will not work.
For full source code refer to the link at the bottom.
#include <SPI.h>
#include <Ethernet.h>
#include <dht.h>
#include <PubSubClient.h>
#define DHT11_PIN A0
#define POLLINTERVAL 10000 // 10seconds interval
#define CLIENTID "ArduinoTempHumSensor"
#define TOPICNAME "DHT11/temphum"
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x25, 0xC4 };
byte server[] = { 212, 72, 74, 21 }; // "broker.mqttdashboard.com"
dht DHT;
PubSubClient arduinoClient(server, 1883, callback); // We don't use it
char charSensorVal[20];
double humidity = 0.0; // Sensed Humidity
double temperature = 0.0; // Sensed Temperature
int seq = 0;
void setup() {
Serial.begin(9600);
Ethernet.begin(mac);
// Connect to the MQTT Server - broker.mqttdashboard.com
beginConnection();
}
void loop() {
if((millis() % POLLINTERVAL) == 0) {
if(getSensorVal()){
dtostrf(temperature, 5, 2, charSensorVal);
charSensorVal[5] = ',';
dtostrf(humidity, 5, 2, charSensorVal + 6);
// One line publishing
arduinoClient.publish(TOPICNAME, charSensorVal);
Serial.print(seq++);
Serial.print(":");
Serial.println(charSensorVal);
}
}
}
void beginConnection() {
Serial.println("Try connect to MQTT server");
int connRC = arduinoClient.connect(CLIENTID); // MQTT Broker connection
if(!connRC) {
Serial.println(connRC);
Serial.println("Could not connect to MQTT Server");
delay(100);
exit(-1);
}
else {
Serial.println("Connected to MQTT Server...");
}
}
void callback(char* topic, uint8_t* payload, unsigned int length) {}
byte getSensorVal() {
if(DHT.read11(DHT11_PIN) == DHTLIB_OK) {
humidity = DHT.humidity;
temperature = DHT.temperature;
return 1;
}
else return 0;
}
Full codes can be found in following links- MQTT_Pub_DHT.ino:
https://github.com/michelleseo/Arduino_Web/blob/master/MQTT/MQTT_Pub_DHT/MQTT_Pub_DHT.ino
No comments:
Post a Comment