Testing the sensor

We are now going to use the sensor. Again, remember that we are using the Arduino IDE, so we can code just like we would do using an Arduino board. Here, we will simply print the value of the temperature inside the Serial monitor of the Arduino IDE. If it has not been done yet, install the Adafruit DHT sensor library using the Arduino IDE library manager.

This is the complete code for this part:

// Libraries
#include "DHT.h"

// Pin
#define DHTPIN 5

// Use DHT11 sensor
#define DHTTYPE DHT11

// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE, 15);

void setup() {

// Start Serial
Serial.begin(115200);

// Init DHT
dht.begin();
}

void loop() {

// Reading temperature and humidity
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();

// Display data
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %	");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C ");

// Wait 2 seconds between measurements.
delay(2000);

}

Let's see the details of the code. You can see that all the measurement part is contained inside the loop() function, which makes the code inside it repeat every 2 seconds.

Then, we read data from the DHT11 sensor, and print the value of the temperature and humidity on the Serial port.

Note

Note that the complete code can also be found inside the GitHub repository for the project:

https://github.com/openhomeautomation/iot-esp8266

Now let's start with the steps to test the sensor:

  1. Paste the previous code into the Arduino IDE. Then, go to Tools | Boards, and select Generic ESP8266 Module. Also select the correct Serial port that corresponds to the FTDI converter you are using.
  2. After that, we need to put the board in bootloader mode, so we can program it. To do so, connect GPIO pin 0 to the ground, via the cable we plugged into GPIO 0 before.
  3. Then, power cycle the board by switching the power supply off and then on again.
  4. Now, upload the code to the board and open the Serial monitor when this is done. Also, set the Serial monitor speed to 115200.
  5. Now, disconnect the cable between GPIO 0 and GND, and power cycle the board again.

You should immediately see the temperature and humidity readings inside the Serial monitor. My sensor was reading around 24 degrees Celsius when I tested it, which is a realistic value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.109