Skip to content

Instantly share code, notes, and snippets.

@andriyadi
Last active June 9, 2016 16:40
Show Gist options
  • Save andriyadi/b0bbf0fbe989de7bb275da89e30b9c2a to your computer and use it in GitHub Desktop.
Save andriyadi/b0bbf0fbe989de7bb275da89e30b9c2a to your computer and use it in GitHub Desktop.
Source code used in this video: https://www.youtube.com/watch?v=zr2W1vJ61S4
#include "DHT.h"
#include <Bridge.h>
#include <YunClient.h>
#include <MQTTClient.h>
YunClient net;
MQTTClient client;
#define DHTPIN 5 //What digital pin we're connected to
#define DHTTYPE DHT11 //DHT 11
DHT dht(DHTPIN, DHTTYPE);
unsigned long lastMillis = 0;
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
Bridge.begin();
client.begin("iotid.cloudapp.net", net);
connect();
}
void connect() {
Serial.print("connecting...");
while (!client.connect("arduino", "andri", "YOUR_OWN_PASSWORD")) {
Serial.print(".");
delay(1000);
}
Serial.println("\nconnected!");
client.subscribe("andri/control");
}
void loop() {
//MQTT client loop
client.loop();
if(!client.connected()) {
connect();
}
// publish a message roughly 30 seconds.
if(millis() - lastMillis > 30000) {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.println(" *F\t");
lastMillis = millis();
String realMsg = "{\"temp\":" + String(t) + ", \"hum\": " + String(h) + "}";
client.publish("andri/dht11", realMsg);
}
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
Serial.print("incoming: ");
Serial.print(topic);
Serial.print(" - ");
Serial.print(payload);
Serial.println();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment