Monday, October 24, 2016

Posting DHT11 Values to ThingSpeak Using Nodemcu (Tutorial-5)

Nodemcu is great WiFi chip and we started our journey with some basic applications, which are as follow:
Getting Started with Nodemcu in Arduino IDE
Getting Temperature and Humidity Values on Phone
Controlling Devices Over WiFi using Phone
Controlling Devices Over WiFi Using Phone without WiFi Router

The common thing in all these posts is that the Nodemcu is present in the local network and that’s why you will get data and can control devices, within your network boundaries. 
For example: You can control devices only from your home network, and not from outside world.
So now we will go beyond the boundaries of our local network and access the Nodemcu over the Internet, and in these series of post, firstly I would like to see the temperature and humidity values of my home measured by Nodemcu using DHT11 sensor, over Internet from any other location or on any other network, and for Completing this task, we will use ThingSpeak.
Block Diagram
What is ThingSpeak?
ThingSpeak is an IoT platform for data collection and analytics that serves as a bridge connecting edge node devices such as temperature, humidity, pressure etc. sensors to collect data and data exploratory analysis software to analyze data.
ThingSpeak serves as the data collector which collects data from edge node devices (Nodemcu/ESP8266 is this case) and also enables the data to be pulled into a software environment for historical analysis of data.
The primary element of ThingSpeak activity is the channel, which contains data fields, location fields, and a status field. After you create a ThingSpeak channel, you can write data to the channel, process and view the data with MATLAB code, and react to the data with tweets and other alerts.

The typical ThingSpeak workflow lets you:
  • Create a Channel and collect data
  • Analyze and Visualize the data
  • Act on the data using any of several Apps
So in the post, we will measure the temperature and humidity values using DHT11 sensor with the help of Nodemcu module and then send these values to ThingSpeak channel, and by doing this you can see the temperature and humidity values of your home from any corner of the world using ThingSpeak.

Follow the following steps to configure:

  • Sign In into ThingSpeak account, by using ThingSpeak account or using MathWorks account. 
  • Click on My Channels.
  • On the channel page, click on New Channel.

Click on New Channel

  • As we are using DHT11 sensor to measure the temperature and humidity values, we will name our channel as Measurements (You can choose any other desired name).
  • Provide some description though it’s not mandatory.
  • Update Field-1 with Temperature and Field-2 with Humidity (Number of fields can be updated as per your project requirement).
  • You can select some other settings as well and after that you can save your channel.
  • After saving the channel you will see 5 tabs, Private View, Public View, Channel Setting, API Keys, Data Import/Export.
5 Tabs of the Channel.

  • You can modify the Title, X-Axis, Y-Axis, scales of Field-1 and Field-2 for Private View and Public View of the Channel.
Change Setting

  • Now time to update the Nodemcu code written in Arduino IDE, copy the Channel ID and Write API Key from API Keys tab and update it in Arduino IDE program.
Update Channel ID and Write API Key in Nodemcu Firmware

  • Build your project and flash the Nodemcu with the updated code, and after that you will see the temperature and humidity graphs on the ThingSpeak channel, as shown in the below images.
ThingSpeak Channel After Few Minutes of running the Firmware.
ThingSpeak Channel After 8 Hours

You can download the ThingSpeak library for Arduino by clicking here.
The code written in Arduino IDE for Nodemcu is as follow:
#include <DHT.h>  
#include <ESP8266WiFi.h>  
#include <WiFiClient.h>  
#include <ThingSpeak.h>  
#define DHTPIN D5  
#define DHTTYPE DHT11  
DHT dht(DHTPIN, DHTTYPE);  
const char* ssid = "WiFiName";  
const char* password = "Password";  
WiFiClient client;  
unsigned long myChannelNumber = 174314;  
const char * myWriteAPIKey = "JQPT38EM56K0MJM1";  
uint8_t temperature, humidity;  
void setup()  
{  
  Serial.begin(115200);  
  dht.begin();  
  delay(10);  
  // Connect to WiFi network  
  Serial.println();  
  Serial.println();  
  Serial.print("Connecting to ");  
  Serial.println(ssid);  
  WiFi.begin(ssid, password);  
  while (WiFi.status() != WL_CONNECTED)  
  {  
   delay(500);  
   Serial.print(".");  
  }  
  Serial.println("");  
  Serial.println("WiFi connected");  
  // Print the IP address  
  Serial.println(WiFi.localIP());  
  ThingSpeak.begin(client);  
}  
void loop()   
{  
  static boolean data_state = false;  
  temperature = dht.readTemperature();  
  humidity = dht.readHumidity();  
  Serial.print("Temperature Value is :");  
  Serial.print(temperature);  
  Serial.println("C");  
  Serial.print("Humidity Value is :");  
  Serial.print(humidity);  
  Serial.println("%");  
  // Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different  
  // pieces of information in a channel. Here, we write to field 1.  
  if( data_state )  
  {  
   ThingSpeak.writeField(myChannelNumber, 1, temperature, myWriteAPIKey);  
   data_state = false;  
  }  
  else  
  {  
   ThingSpeak.writeField(myChannelNumber, 2, humidity, myWriteAPIKey);  
   data_state = true;  
  }  
  delay(30000); // ThingSpeak will only accept updates every 15 seconds.  
} 


You can also download the ThingSpeak mobile application ThingView from Google Play Store and directly view the channel graphs in ThingView Application.

Following are the steps to setup the ThingView Application on your Android Phone.

Open ThingView Application, and click on Add Button.

After Clicking on Add button, Enter the Channel ID, then Search and select the Channel.

Your Channel is Added, you can view the Graphs directly on your Smart Phone.
Following are the screenshots of the graphs taken from the ThingView mobile application.




All steps given above are documented in this video, so have a look at this video.


Also Read the following posts:

43 comments:

  1. Hi there! I need to use 2 pcs DHT22. How should I modify the code for displaying 4 fields in Tingspeak?

    ReplyDelete
    Replies
    1. You can use this library to get the temperature and humidity data from DHT22 sensor, ofcourse interfacing two sensors is very much possible and simple, just define two objects, and then store the temperature and humidity values in four variables.
      Then use the following piece of code to transmit data to ThingSpeak
      ThingSpeak.writeField(myChannelNumber, (Field Number), (DataToTransfer), myWriteAPIKey);

      Delete
  2. Thanks for example, only two improvements

    1. Check error DTH11
    // uint8_t temperature, humidity;
    float temperature = dht.readTemperature();
    float humidity = dht.readHumidity();
    // Check if any reads failed and exit early (to try again).
    if (isnan(humidity) || isnan(temperature) ) {
    Serial.print("Reads failed DTH11");
    delay(1000);
    return;
    }

    2. One write to ThingSpeak

    ThingSpeak.setField(1,temperature);
    ThingSpeak.setField(2,humidity);
    // Write the fields that you've set all at once.
    ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

    ReplyDelete
    Replies
    1. Thanks for suggestion.
      I hope my readers will take suggestion from this comment.

      Delete
    2. may i know y will be read fail? and how to correct it? thanks advance.

      Delete
    3. The response from dht11 is digital pulse and in some cases it might be possible that you didn't read that correctly and missed some pulses.
      In that cases you will not get correct reading.
      The only way to correct such things is to use take carr of boundaries conditions for temperature and humidity values and discard the values if they are not correct.

      Delete
  3. hi i need a help .
    I am doing this same but I need the output on all this mentioned ,(On thingspeak account ,on my local wifi ip and serial monitor simaltaneously )
    If it is possible then tell me

    ReplyDelete
    Replies
    1. I think it might​be possible, what problem you are facing.
      Try and experiment, and update the results.

      Delete
  4. i used your code but could not get the output.arduino ide is showing this error,

    In file included from C:\Users\DELL INSPIRON\Documents\Arduino\libraries\DHT_sensor_library\DHT_U.cpp:22:0:

    C:\Users\DELL INSPIRON\Documents\Arduino\libraries\DHT_sensor_library\DHT_U.h:25:29: fatal error: Adafruit_Sensor.h: No such file or directory

    #include

    ^

    compilation terminated.

    exit status 1
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

    compilation terminated.

    exit status 1
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).


    ReplyDelete
    Replies
    1. Adafruit changes it,s library a little, the following phrase is taken from their website.

      IMPORTANT: As of version 1.3.0 of the DHT library usefull you will need to install the library Adafruit_Sensor, All which is available from the Arduino library manager:

      So in short download this library from the link given below
      https://github.com/adafruit/Adafruit_Sensor

      Add this to Arduino Libraries folder and you are done.
      This is the latest changes to the DHT library, which is causing this error, earlier it was not present that's why my program runs without any problem.
      Just download and add the file, you will be able to compile your code.

      Delete
  5. I followed your instructions but on Think speak channel its not showing any value. plz help me....

    ReplyDelete
    Replies
    1. Probably you have done something wrong.
      Nodemcu must be connected to internet, make sure you are..

      Delete
  6. #include
    #include
    #include
    #include
    #define DHTPIN D5
    #define DHTTYPE DHT11
    DHT dht(DHTPIN, DHTTYPE);
    const char* ssid = "sheetal";
    const char* password = "abcdefgh";
    WiFiClient client;
    unsigned long myChannelNumber = 262079;
    const char * myWriteAPIKey = "CLG8GD0GLXGN7N8V";
    uint8_t temperature, humidity;
    void setup()
    {
    Serial.begin(115200);
    dht.begin();
    delay(10);
    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
    // Print the IP address
    Serial.println(WiFi.localIP());
    if(ThingSpeak.begin(client))
    { Serial.println("start uploading");
    }
    }
    void loop()
    {
    static boolean data_state = false;
    temperature = dht.readTemperature();
    humidity = dht.readHumidity();
    Serial.print("Temperature Value is :");
    Serial.print(temperature);
    Serial.println("C");
    Serial.print("Humidity Value is :");
    Serial.print(humidity);
    Serial.println("%");
    // Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
    // pieces of information in a channel. Here, we write to field 1.
    if( data_state )
    {
    ThingSpeak.writeField(myChannelNumber, 1, temperature, myWriteAPIKey);
    data_state = false;
    }
    else
    {
    ThingSpeak.writeField(myChannelNumber, 2, humidity, myWriteAPIKey);
    data_state = true;
    }
    delay(30000); // ThingSpeak will only accept updates every 15 seconds.
    }
    in above code ,changed the apiwrite key,channel no,wifi name and password ...still its not working

    ReplyDelete
  7. and serial monitor output is
    Connecting to sheetal
    .......
    WiFi connected
    192.168.43.94
    start uploading
    Temperature Value is :255C
    Humidity Value is :255%

    ReplyDelete
    Replies
    1. sorry for disturb. i having the same problem over here, can u solve it ad? :-)

      Delete
    2. Check your connection or try with some different sensor.
      Make sure that data line is pulled high and also use a capacitor between vcc and gnd

      Delete
  8. thanks for your previous help.one more problem i am facing that i am not able to get the correct reading most of time(i.e. most of time it is showing 255c temperature and 255 humity).please give the solution.

    ReplyDelete
    Replies
    1. In this case i can only suggest fee things:
      - Stable power supply, use capacitor between vcc and gnd, to prevent fluctuations.
      - Check the pull-up resistors on data line and make sure the value is correct and it is properly connected.
      - Also check connection, make sure that they are not loose.
      - Check for any dry solder on pcb, which can also create problems.

      Delete
  9. If i wanna upload 3 values... Temperature, humidity and Distance( Sonar Sensor) then what changing i should have to make in coding... Plz help

    ReplyDelete
    Replies
    1. You have to change the Arduino Code and Android Code.
      In Arduino code you just have to update the sonar data into OutBuffer array before transmitting.
      And the same thing needs to be done for Android Code.
      But this post has only apk for for Android code.
      Contact us at matlab.academy.com for android source files of this project.

      Delete
  10. I'm using dht22 and is this the result, 255
    Can anyone help?

    ReplyDelete
    Replies
    1. I can only suggest.
      Did you use
      #define DHTTYPE DHT22 instead of
      #define DHTTYPE DHT11
      From the results, it looks that, your DHT22 sensor is not giving any response and the data pin stays at high always, that's why you are getting 255 value.

      Delete
  11. This worked well, thank you. However, when I exported recorded data from ThingSpeak, I see that there is around 36 seconds of delay between the logged temperature and humidity data (ie: Around 72 seconds delay between consecutive temp / humidity readings).
    What could account for this? Is there any way to reduce this delay, so that I can get simultaneous humidity/temperature values?

    ReplyDelete
    Replies
    1. Actually Thingspeak is a free server and free version only allow data update with minimum time of 15secs. In any case you will get 15 sec delay.
      If you send data quickly then that, ThingSpeak will reject it.

      Delete
  12. Replies
    1. In the above program, i already used two fields Humidity and Temperature, so you can add more fields in the similar way.

      Delete
  13. Replies
    1. This is tutorial 5.
      Please check the previous tutorials, you will get the path of dht library.
      By the it is from Adafruit and you can directly download it from there.

      Delete
  14. Replies
    1. I have shown the complete video with the results, so that means it is working.
      So it's better to tell at what phase you are having problem, so that I can help.

      Delete
  15. hello , the data at thingspeak server for temp and humidity is not updated at the same time. temperature data does not update frequent compare to humidity . may i know how to fix this?

    ReplyDelete
    Replies
    1. Yes both are not updated at the same time.
      To do that, use this.

      ThingSpeak.setField(1,temperature);
      ThingSpeak.setField(2,humidity);
      // Write the fields that you've set all at once.
      ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

      Regarding your another question, I didn't see this problem.
      But still you can check the method above and I hope it will solve your problem.

      Delete
  16. Hello Thanks for your sketch. I have a problem to include the suggested improvments. Can you please show how to implement them in the code?

    ReplyDelete
  17. IAM getting board error should I download any drivers for that I downloaded dht library IAM getting nodmcu1.0 error

    ReplyDelete
  18. "• Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updating IOT Online Training
    "

    ReplyDelete
  19. Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updating IOT online training

    ReplyDelete
  20. sir i am getting following error while compiling...
    exit status 1
    Error compiling for board LOLIN(WEMOS) D1 R2 & mini.

    how to fix..

    ReplyDelete
  21. Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updating IOT online training

    ReplyDelete
  22. the program is incomplete and this the mistake i corrected .Thank you for this awsome guidance
    if( data_state )
    {
    ThingSpeak.writeField(myChannelNumber,1,temperature,myWriteAPIKey);
    data_state = false;
    ThingSpeak.writeField(myChannelNumber,2,humidity,myWriteAPIKey);
    data_state = false;

    }
    else
    {
    ThingSpeak.writeField(myChannelNumber,1,temperature,myWriteAPIKey);
    data_state = true;
    ThingSpeak.writeField(myChannelNumber,2,humidity,myWriteAPIKey);
    data_state = true;
    }
    delay(300);//ThingSpeak will only accept updates every 15 seconds
    }

    ReplyDelete