Skip to content

Instantly share code, notes, and snippets.

@mammenj
Last active May 11, 2016 06:45
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 mammenj/ae2715c54c86ee3a19025beb2daa0859 to your computer and use it in GitHub Desktop.
Save mammenj/ae2715c54c86ee3a19025beb2daa0859 to your computer and use it in GitHub Desktop.
This code has been based on many other codebase available on the net. The code below allows you to measure temperature using ESP8266 with DHT22 sensor. It will post the temperature to test mqtt server here http://test.mosquitto.org/gauge/
// This code was based on the below codebase and modified for my project
// https://gist.github.com/chaeplin/ee0fef774d2e79e0c236
// https://github.com/adafruit/DHT-sensor-library/blob/master/examples/DHTtester/DHTtester.ino
// https://gist.github.com/igrr/7f7e7973366fc01d6393
// https://github.com/iot-playground/Arduino/blob/master/ESP8266ArduinoIDE/DS18B20_temperature_sensor/DS18B20_temperature_sensor.ino
// This sketch was flashed and tested on ESP8266 ESP-201 board. It should work on other variants as well.
// import from https://github.com/adafruit/DHT-sensor-library
#include "DHT.h"
// import from https://github.com/knolleary/pubsubclient
#include <PubSubClient.h>
// included in the Arduino ESP8266 IDE
// https://github.com/esp8266/Arduino
#include <ESP8266WiFi.h>
// DHT Sensor parameters
#define DHTPIN 2 // what digital pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
// WIFI parameters
#define WIFI_SSID "***"
#define WIFI_PASS "***"
// MQTT parameters
// Using http://test.mosquitto.org/gauge/ for demo temperature
// #define MQTT_SERVER "iot.eclipse.org"
#define MQTT_SERVER "test.mosquitto.org"
#define MQTT_PORT 1883
// MQTT topic where the temperature is published
char* topic = "temp/random";
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
// WiFi client
WiFiClient wifiClient;
//MQTT client
PubSubClient client(MQTT_SERVER, MQTT_PORT, callback, wifiClient);
String macToStr(const uint8_t* mac) {
String result;
for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);
if (i < 5)
result += ':';
}
return result;
}
// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("<<--- Connecting to WIFI --->>");
// WIFI Connection
wifiConnect();
Serial.println("<<--- Connecting to *MQTT* --->>");
// MQTT Connection
connectMQTT();
Serial.println("<<--- Begin Temperature and Humidity measurement --->>");
// Initialize DHT sensor
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// 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;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
// send temperature and humidity to MQTT Server
sendTeperature(t);
}
void connectMQTT() {
// Generate client name based on MAC address and last 8 bits of microsecond counter
String clientName;
clientName += "jsmEsp8266-";
uint8_t mac[6];
WiFi.macAddress(mac);
clientName += macToStr(mac);
clientName += "-";
clientName += String(micros() & 0xff, 16);
Serial.print("Connecting to MQTT ");
Serial.print(MQTT_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);
if (client.publish(topic, "hello from ESP8266")) {
Serial.println("Publish ok");
}
else {
Serial.println("Publish failed");
}
} else {
Serial.println("MQTT connect failed");
Serial.println("Will reset and try again...");
abort();
}
}
void wifiConnect() {
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void sendTeperature(float t) {
String payload = "";
payload += t;
payload += "";
if (client.connected()) {
Serial.print("Sending payload to topic: ");
Serial.println(topic);
Serial.println(payload);
if (client.publish(topic, (char*) payload.c_str())) {
Serial.println("Published ok");
} else {
Serial.println("Publish failed");
}
} else {
connectMQTT()
}
// Wait for 5 secs
delay(5000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment