Skip to content

Instantly share code, notes, and snippets.

@yoggy
Created June 3, 2014 10:23
Show Gist options
  • Save yoggy/329fe7fe472320121e2f to your computer and use it in GitHub Desktop.
Save yoggy/329fe7fe472320121e2f to your computer and use it in GitHub Desktop.
//
// mqtt_pub_dht11.ino - mqtt publish sample for Arduino Ethernet
//
// This program uses the following libraries.
// https://github.com/knolleary/pubsubclient
// https://github.com/virtuabotix/DHT11LIB
//
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <dht11.h>
#include <avr/wdt.h>
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x12};
char *server = "mqtt.server.example.com";
int port = 1883;
char *username = "username";
char *password = "password";
char *topic = "home_dht11";
EthernetClient ether_client;
PubSubClient mqtt_pub_client(server, port, NULL, ether_client);
dht11 DHT11;
int DHT11_PIN = 2;
int LED_PIN = 9;
void reboot() {
Serial.println("now rebooting...");
wdt_enable(WDTO_8S);
while(true) {
digitalWrite(LED_PIN, HIGH);
delay(200);
digitalWrite(LED_PIN, LOW);
delay(200);
}
}
void print_my_ip() {
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
while (!Serial) {
}
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
delay(3000);
reboot();
}
print_my_ip();
if (mqtt_pub_client.connect("mqtt_pub_client", username, password) == false) {
Serial.println("Failed to connect MQTT broker...");
delay(3000);
reboot();
}
Serial.print("connection start...");
Serial.print("mqtt_server=");
Serial.print(server);
Serial.print(", port=");
Serial.print(port);
Serial.println();
wdt_enable(WDTO_8S);
DHT11.attach(DHT11_PIN);
}
void loop() {
digitalWrite(LED_PIN, HIGH); // blink led...
// read temperature & humidity
int chk = DHT11.read();
switch (chk){
case 0:
Serial.println("DHT11.read() : read success");
break;
case -1:
Serial.println("DHT11.read() : checksum error");
reboot();
break;
case -2:
Serial.println("DHT11.read() : time out error");
reboot();
break;
default:
Serial.println("DHT11.read() : unknown error");
reboot();
break;
}
// build payload
char payload[256];
snprintf(payload, 256, "{\"temperature\": %d, \"humidity\": %d, \"tick_count\":%ld}",
DHT11.temperature,
DHT11.humidity,
millis());
Serial.print("publish...payload=");
Serial.println(payload);
wdt_reset();
// publish message
if (mqtt_pub_client.publish(topic, payload) == false) {
Serial.print("publish failed...");
reboot();
}
wdt_reset();
mqtt_pub_client.loop();
wdt_reset();
delay(200);
digitalWrite(LED_PIN, LOW); // blink led...
delay(4800);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment