Easy, Cheap Web enabled Temperature and Humidity Sensor – With Ubidots

Some of the links below are affiliate links, meaning that I will earn a commission if you click and make a purchase. This is at no extra cost to yourself.

This article is an accompaniment to this youtube video (https://www.youtube.com/watch?v=yqmOp7m4szA). See below the code for the two examples mentioned in the video. Don’t forget to visit Ubidots: http://bit.ly/ubidotsCC

The parts I use in this video:

Wemos D1 Mini and DHT22 (AM2032) Sensor


//Make sure you setup the ESP8266 Board
//File - Preferences - Additional Board References URL
//http://arduino.esp8266.com/versions/2.3.0/package_esp8266com_index.json

#include "DHT.h" //https://github.com/adafruit/DHT-sensor-library

#define DHTPIN 5 //Pin D1

#define DHTTYPE DHT22 //Temp and Humidity Sensor we are using


DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  Serial.println("Initialised...");

  dht.begin();
}

void loop() {

  delay(1500);
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();


  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print("   Temperature: ");
  Serial.println(t);
}

IOT: Connecting to WiFi and uploading to Ubidots

#include "DHT.h" //https://github.com/adafruit/DHT-sensor-library
#include <ESP8266WiFi.h>
#include "UbidotsESPMQTT.h"
#define DHTPIN 5 //Pin D1

#define DHTTYPE DHT22 //Temp and Humidity Sensor we are using


#define TOKEN "xxxxxxxxxxxxxxxxxxxxxxxxx" // Your Ubidots TOKEN

#define WIFINAME "SSID" //Your SSID
#define WIFIPASS "PASSWORD" //Your Wifi Pass

DHT dht(DHTPIN, DHTTYPE);


Ubidots client(TOKEN);

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();
}

void setup() {
  client.setDebug(true);
  Serial.begin(115200);
  client.wifiConnection(WIFINAME, WIFIPASS);
  client.begin(callback);
  
  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  dht.begin();
}

void loop() {


  float h = dht.readHumidity(); //Humidity in %
  float t = dht.readTemperature(); //Temp in Celsius

  if (isnan(h) || isnan(t)) { //Did the sensor read fail?
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print("   Temperature: ");
  Serial.println(t);

  if(!client.connected()){
      client.reconnect();
  }

  client.add("temperature", t);
  client.add("humidity", h);
  client.ubidotsPublish("Temp_Humidity_SmallGH");
  client.loop();

  delay(60000);
  


}
Shopping Basket