Earn Maker Points on Every Order! Learn More!

Upload Sensor Data to ThingSpeak using NodeMCU

Back to Blog
Upload Sensor Data to ThingSpeak using NodeMCU - Upload Sensor Data to ThingSpeak using NodeMCU - Upload Sensor Data to ThingSpeak using NodeMCU - Upload Sensor Data to ThingSpeak using NodeMCU

Upload Sensor Data to ThingSpeak using NodeMCU

ThingSpeak is an Open-Source IoT application and API to store and retrieve data from Hardware devices and Sensors. It uses HTTP Protocol over the Internet or LAN for its communication. The MATLAB analytics is included to analyze and visualize the data received from your Hardware or Sensor Devices.

We can create channels for each and every sensor data. These channels can be set as private channels or you can share the data publically through Public channels. The commercial features include additional features. But we will be using the free version as we doing it for educational purpose.

You can make projects like Weather Station, Tide Prediction, Counter and Many More.

Features:

  • Collect data in private channels.
  • Share Data with Public Channels
  • REST API and MQTT APIS
  • MATLAB® Analytics and Visualizations.
  • Worldwide Community

In this tutorial, we will be using an LDR to plot its light Intensity level on ThingSpeak using NodeMCU. We will program the NodeMCU to read and store the LDR data into a variable and then upload it to ThingSpeak using its channel name and API key. The NodeMCU should be connected to the internet via Wi-Fi. We will see how to create ThingSpeak Channels and configure it on NodeMCU.

Hardware Required:

  • NodeMCU
  • LDR Module
  • 10K Ohm Resistor
  • Jumper Wires
  • Breadboard (Optional)

Circuit Diagram:

NodeMCU LDR_bb

 

Once the hardware is set up, We can go ahead and create our ThingSpeak Channel.

Step 1: Go to https://thingspeak.com/ and create your ThingSpeak Account if you don’t have. Login to Your Account.

Step 2: Create a Channel by clicking ’New Channel’.

1.Sign In

Step 3: Enter the channel details.

Name: Any Name

Description: Optional

Field 1: Light Intensity LDR – This will be displayed on the analytics graph. If you need more than 1 Channels you can create for additional Sensor Data.

Save this setting.

3.Channel Details

Step 4: Now you can see the channels. Click on the ‘API Keys’ tab. Here you will get the Channel ID and API Keys. Note this down.

4.Channel ID API Key

Step 5: Open Arduino IDE and Install the ThingSpeak Library. To do this go to Sketch>Include Library>Manage Libraries. Search for ThingSpeak and install the library.

5.Install Thingspeak Library

Step 6: Now we need to modify the program with your credentials.

In the below code you need to change your Network SSID, Password and your ThingSpeak Channel and API Keys.

Replace the following content in the code,

Your SSID Here’ – Your Wi-Fi Name

Your Password Here’ – Your Wi-Fi Password

YYYYYY’ – Your ThingSpeak Channel Number (without Quotes)

XXXXXXXXXXX’ – Your Thing Speak API Key.

 

Code:

#include <ESP8266WiFi.h>;

#include <WiFiClient.h>;

#include <ThingSpeak.h>;

const char* ssid = "Your SSID Here"; //Your Network SSID

const char* password = "Your Password Here"; //Your Network Password

int val;

int LDRpin = A0; //LDR Pin Connected at A0 Pin



WiFiClient client;

unsigned long myChannelNumber = YYYYYY; //Your Channel Number (Without Brackets)

const char * myWriteAPIKey = "XXXXXXXXXXXXXXX"; //Your Write API Key

void setup()

{

Serial.begin(9600);

delay(10);

// Connect to WiFi network

WiFi.begin(ssid, password);



ThingSpeak.begin(client);

}



void loop()

{

val = analogRead(LDRpin); //Read Analog values and Store in val variable

Serial.print(val); //Print on Serial Monitor

delay(1000);

ThingSpeak.writeField(myChannelNumber, 1,val, myWriteAPIKey); //Update in ThingSpeak



delay(100);

}

Upload the code. Once it is connected to Wi-Fi the data will start uploading to the ThingSpeak Channel. You can now open your Channel and see the data changes plotted on the ThingSpeak.

6.Channel Output

Share this post

Comments (116)

  • rahul

    thanks for the information, i need upload data in two filed i tried but it upload one filed only can you guide me

    March 22, 2019 at 12:24 PM
    • Sharath

      Did you added the Second Channel on your code.

      Create one more channel as ‘myChannelnumber2 = 2ndYYYY’ and API Key variable 2ndXXXXXXXXXXX.
      and then add one more thinngspeak writefield and put the myChannelnumber2 and myWriteAPIKey2.

      March 22, 2019 at 1:32 PM
      • Sayali

        Sir,
        I want to read value of D0 and D1 of esp8266 and upload it on thingspeak channel.can you please provide code for same.I tired but channel is not updating with binary value,below is code.
        #include ;

        #include ;
        #include ;
        const char* ssid = “xxxxxx”; //Your Network SSID
        const char* password = “xxxxxx”; //Your Network Password

        int output1 = D0; // the number of the pushbutton pin
        int output2 = D1; // the number of the LED pin
        int output1State = 0; // variable for reading the pushbutton status
        int output2State = 0; // variable for reading the pushbutton status

        void setup() {
        unsigned long myChannelNumber = xxxxx; //Your Channel Number (Without Brackets)

        const char * myWriteAPIKey = “xxxxxxxx”; //Your Write API Key
        Serial.begin(9600);
        Serial.print(“begin”);
        // initialize the LED pin as an output:
        pinMode(output1, OUTPUT);
        pinMode(output2, OUTPUT);
        }

        void loop() {

        output1State = digitalRead(output1);
        output2State = digitalRead(output2);

        // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
        if (output1State == HIGH) {
        Serial.println(“High D0 “);
        }
        else {
        Serial.println(“LOW D0 “);
        ThingSpeak.writeField(myChannelNumber, 1,output1, myWriteAPIKey);
        }
        delay(30);
        if (output2State == HIGH) {
        Serial.println(“High D1 “);

        }

        else {
        Serial.println(“LOW D1 “);
        ThingSpeak.writeField(myChannelNumber, 1,output2, myWriteAPIKey);
        }
        }

        May 27, 2019 at 7:56 PM
        • Sharath

          You are updating the channel only when the pin is low. You also have to update if it is high. Then only it will show you both. Otherwise, it will update only the LOW Signals. Also, you are updating both values on the same channel. If you are aware then it will be fine.

          Also, check out this blog, It actually works same, but it has both analog & digital – https://www.factoryforward.com/automatic-street-light-thingspeak-cloud/

          May 27, 2019 at 10:18 PM
  • vivek

    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed
    this error show in program

    March 27, 2019 at 9:24 PM
    • Sharath

      Check with another quality microUSB Cable (Original Phone cables preferred). If your cable is too long it might have some power loss & have high resistances so the data won’t be perfect and difficult to sync.

      March 28, 2019 at 10:00 AM
    • NARENTHIRA PRASATH D

      Tools -> Board: NodeMCU 0.9 (ESP 12 Module)

      And

      Tools -> Upload Speed: 115200

      April 19, 2019 at 10:32 PM
  • Mark

    Hello,

    Could you possibly help me with posting ECG value from the AD8232 Heart rate sensor using the nodemcu? I just need a little help with the code and sending the data to thingspeak

    March 31, 2019 at 11:48 AM
    • Sharath

      Did you have the Reset Problem in NodeMCU while using ThingSpeak?

      April 2, 2019 at 1:53 PM
  • Zigg

    how to send multiple data to thingspeak

    April 2, 2019 at 2:25 AM
    • Sharath

      #include "ThingSpeak.h"
      #include

      char ssid[] = "YourSSID"; // your network SSID (name)
      char pass[] = "YourPassword"; // your network password
      int keyIndex = 0; // your network key Index number (needed only for WEP)
      WiFiClient client;

      unsigned long myChannelNumber = YYYYYY; //Your Channel Number
      const char * myWriteAPIKey = "XXXXXXXXXXXXXXXXX"; //Your API Key

      // Initialize our values
      int number1 = 0; //Dummy Values, consider it from sensors
      int number2 = random(0,100); //Dummy random Values
      int number3 = random(0,100); //Dummy random Values
      int number4 = random(0,100); //Dummy random Values
      String myStatus = "";

      void setup() {
      Serial.begin(115200); // Initialize serial

      WiFi.mode(WIFI_STA);
      ThingSpeak.begin(client); // Initialize ThingSpeak
      }

      void loop() {

      // set the fields with the values
      ThingSpeak.setField(1, number1); //Number 1 Values updated to field 1
      ThingSpeak.setField(2, number2); //to field 2
      ThingSpeak.setField(3, number3); //to field 3
      ThingSpeak.setField(4, number4); //to Field 4

      // figure out the status message
      if(number1 > number2){
      myStatus = String("field1 is greater than field2");
      }
      else if(number1 < number2){ myStatus = String("field1 is less than field2"); } else{ myStatus = String("field1 equals field2"); } // set the status ThingSpeak.setStatus(myStatus); // write to the ThingSpeak channel int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); if(x == 200){ Serial.println("Channel update successful."); } else{ Serial.println("Problem updating channel. HTTP error code " + String(x)); } // change the values number1++; if(number1 > 99){
      number1 = 0;
      }
      number2 = random(0,100);
      number3 = random(0,100);
      number4 = random(0,100);

      delay(20000); // Wait 20 seconds to update the channel again
      }

      April 2, 2019 at 1:51 PM
  • Anson A Akkara

    I am getting error saying

    ‘client’ was not declared in this scope

    April 6, 2019 at 8:23 PM
    • Sharath

      Did you installed these Libraries?
      ESP8266WiFi.h;

      WiFiClient.h;

      It will be available in the ‘Arduino Core for ESP8266 Library’ by default.
      https://github.com/esp8266/Arduino

      Download> Extract> Navigate to Libraries Folder>Copy and paste it in Arduino Libraries Folder (C:\Program Files (x86)\Arduino\libraries)

      April 8, 2019 at 2:11 PM
  • kamna jha

    hello sir, i need code for street lights to on/off according to daylight using IR sensor, arduino, nodemcu and Ldr sending data to thingspeak. could you please help me here?

    April 10, 2019 at 7:01 PM
    • Sharath

      Create a variable for LED

      int ledPin = 13;

      Inside Setup:
      pinmode(ledPin,OUTPUT);

      Inside Loop: Create an if else loop according to your requirements

      if(val<100){
      Function you want to perfom when low light
      LED ON/OFF //use digitalwrite
      ThingSpeak.writeField(myChannelNumber, 1,val, myWriteAPIKey); //Update in ThingSpeak
      }
      else{
      Function you want to perfom when High light

      LED ON/OFF
      }

      April 10, 2019 at 7:23 PM
      • kamna jha

        oh my god you replied!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! thank you very much sir.
        you’re really kind.
        i’d use this code and let you know how it worked .
        can i contact you Sir PLEASE from any other platform than this ? please let me know.

        April 13, 2019 at 9:57 PM
        • kamna jha

          one more thing sir i am not using nodemcu instead using just ESP8266 wifi module the basic chip one, could i do it using arduino LDR and IR sensor with it? i have my project presentation on monday, need to complete by tomorrow. it would mean world to me if you helped sir.

          April 13, 2019 at 10:01 PM
          • Sharath

            I didn’t used the ESP8266 chip alone yet. I mostly prefer NodeMCU Dev Board because it has all the necessary circuitry for faster development and its cheap too. If we build that circuitry for flashing mode, voltage regulation & all it becomes costly and eats a lot of time.

            For prototyping projects better go with NodeMCU. ESP8266 Chips are suitable for fully developed projects and for making large qty as they designed the PCB Specifically for that.

            April 14, 2019 at 10:47 AM
  • Mico

    i got zero values distance in my thingspeal graph sir. can you help me?

    April 15, 2019 at 1:30 PM
  • Mico

    im using nodemcu v3 sir.

    April 15, 2019 at 1:34 PM
    • Sharath

      Use Advanced IP Scanner in your phone or desktop to check whether your NodeMCU is connected to the Wi-Fi Network. Also, you have to update your Channel Number and API Key.

      So you have to modify 4 things in the code before uploading.

      April 15, 2019 at 4:02 PM
  • kamna jha

    sir, i am using nodemcu, LDR, IR Sensor, Led
    street light which is our LED will glow when the LDR which will compare with the given threshold value,
    then if IR sensor will detect any objects it will store the data on thingspeak and glow the LED.
    Sir, coulld you please give the code for this? it would be realy helpful.

    April 16, 2019 at 2:16 PM
  • fiqah

    Hello sir, how to send multiple data to thingspeak if I connect NodeMCU to Arduino Uno?

    April 18, 2019 at 8:08 AM
    • Sharath

      Check the previous comment, asked by Zigg. I replied it with the code.

      April 20, 2019 at 12:52 PM
  • wan

    hello sir, can you help me how to connect sound sensor with nodemcu 8266?

    April 22, 2019 at 9:54 PM
    • Sharath

      Sound sensor output will trigger within microseconds. So you need to use delay function and capture that event in a variable. It is same as the push-button example, just add a delay with that. You can use any digital pin like D1,D2,D5,D6,D7,D8.

      April 23, 2019 at 10:18 AM
      • wan

        can i have sample code for sound sensor connect with nodemcu sir?

        April 29, 2019 at 9:17 PM
      • wannn

        can i have sample code for sound sensor connect with nodemcu sir?

        April 29, 2019 at 9:30 PM
        • Sharath

          int soundDetect;

          //Add setup functions here

          void loop(){
          val = analogRead(LDRpin); //Read Analog values and Store in val variable

          if (val>800){
          soundDetect = HIGH;
          Serial.print(val); //Print on Serial Monitor
          //delay(200);
          ThingSpeak.writeField(myChannelNumber, 1,soundDetect, myWriteAPIKey); //Update in ThingSpeak
          }

          int soundDetect = LOW;
          }

          April 30, 2019 at 10:40 AM
          • wannn

            the codes cannot ran in arduino ide. Is it the connection for circuit same like ldr circuit above?

            May 1, 2019 at 4:17 PM
  • Erhylksym

    Hello Sir, can you help me how to connect and send data water level sensor with nodemcu v3?

    April 24, 2019 at 6:44 AM
    • Sharath

      Which water level sensor you are using?

      If it is a digital sensor (Full or Empty status) then

      Change the A0 analog pin to any digital pin of these D1,D2,D5,D6,D7,D8.

      Then, instead of analogRead you need to use digitalRead. That’s it.

      val = analogRead(LDRpin); //Read Analog values and Store in val variable

      val = digitalRead(LDRpin); //Read Digital values and Store in val variable

      April 24, 2019 at 10:41 AM
      • Erhylksym

        thank u sir, i have finish.
        But can you help me how to connect and send data with nodeMCU to Thingspeak ?
        please help me

        April 30, 2019 at 11:36 AM
        • Sharath

          It is the same tutorial only. Instead of LDR, you use the Waterlevel sensor.
          ThingSpeak.writeField(myChannelNumber, 1,val, myWriteAPIKey);

          The val is the variable that holds sensor data. Whatever you mentioned you can modify that variable here.

          April 30, 2019 at 11:50 AM
  • iane

    Hi! Can you help me on connecting the adxl 335 to the thingspeak? Thanks!!

    April 29, 2019 at 7:51 AM
  • SHUBHAM KUMAR TIWARI

    hello sir, i want to upload accelerometer data to thingspeak but i am not able to do so can you provide me the code please.

    May 7, 2019 at 7:29 PM
  • Ayush Kumar Singh

    Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: “Arduino/Genuino Uno”

    In file included from C:\Users\Thakur Ayush\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,

    from C:\Users\Thakur Ayush\Documents\Arduino\AQM_final\AQM\AQM.ino:1:

    C:\Users\Thakur Ayush\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

    compilation terminated.

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    PLEASE HELP

    May 10, 2019 at 6:37 PM
  • Ganesh Ritesh

    Hello!
    I am doing my final year project on underground cable fault detection over IoT.
    I am using an Arduino Uno as microcontroller and ESP8266-12E as WiFi module. Both are communicating serially. I have been able to send data from Arduino Uno to WiFi module that i have checked on the serial monitor of the ESP8266-12E. The WiFi module is also connected to ThingSpeak platform.

    The only problem is that the IoT platform is displaying only zeros on all three fields even if the serial monitor of the WiFi module is receiving different data

    Below is my code uploaded to the ESP8266-12E
    my data from the arduino is uploaded to the WiFi module as follows :
    *864#; it means that the wifi module will check if the string of data starts with ‘*’ and ends with ‘#’ if yes it takes the value in between as
    8 to be data 1
    6 to be data 2
    4 to be data 3

    ESP8266-12E Code

    String apiKey = “GCC8OP2PI5JYIOY3”; // <<<<< YOUR API KEY
    const char* ssid = "Telecom-YCTb"; // <<<<<<<< Your Wi-Fi SSID
    const char* password = "n4mcE5mV"; // <<<<<<< 0)
    {
    delay(100);
    while (Serial.available() > 0)
    {
    buffer1 = Serial.readString();
    if (buffer1[0] == ‘*’)
    {
    if (buffer1[4] == ‘#’)
    {
    Serial.println(buffer1);
    data1 = ((buffer1[1]- 0x30));
    data2 = ((buffer1[2]- 0x30));
    data3 = ((buffer1[3]- 0x30));
    }
    }
    }

    }
    if (client.connect(server, 80))
    {
    String postStr = apiKey;
    postStr += “&field1=”;
    postStr += String(data1);
    postStr += “&field2=”;
    postStr += String(data2);
    postStr += “&field3=”;
    postStr += String(data3);
    postStr += “\r\n\r\n\r\n”;
    client.print(“POST /update HTTP/1.1\n”);
    client.print(“Host: api.thingspeak.com\n”);
    client.print(“Connection: close\n”);
    client.print(“X-THINGSPEAKAPIKEY: ” + apiKey + “\n”);
    client.print(“Content-Type: application/x-www-form-urlencoded\n”);
    client.print(“Content-Length: “);
    client.print(postStr.length());
    client.print(“\n\n”);
    client.print(postStr);
    Serial.println(postStr);
    }
    client.stop();
    Serial.println(“Waiting…”);
    delay(20000);

    May 12, 2019 at 6:25 PM
  • mrrusda12

    Hello sir, How I can sent Serial monitor Arduino to Thingspeak using NodeMCU ?

    May 19, 2019 at 12:56 PM
    • Sharath

      byte myData = Serial.read();
      ThingSpeak.writeField(myChannelNumber, 1,(char)val, myWriteAPIKey); //Update in ThingSpeak

      May 19, 2019 at 3:00 PM
      • mrrusda12

        I Upload this code and still not update . can you help me, i use RX TX pin arduino to Tx Rx pin Nodemcu for serial monitor.

        #include ;
        #include ;
        #include ;
        const char* ssid = “POCOPHONE”; //Your Network SSID
        const char* password = “wsmining”; //Your Network Password
        int val;
        WiFiClient client;
        unsigned long myChannelNumber = 783537; //Your Channel Number (Without Brackets)
        const char * myWriteAPIKey = “25VJ25D5ANV43P9B”; //Your Write API Key

        void setup()
        {
        Serial.begin(9600);
        while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
        }
        delay(10);
        // Connect to WiFi network
        WiFi.begin(ssid, password);
        ThingSpeak.begin(client);
        }

        void loop(){
        if (Serial.available())
        {
        byte val = Serial.read();
        delay(1000);
        ThingSpeak.writeField(myChannelNumber, 1,(char)val, myWriteAPIKey);
        delay(100);
        }
        }

        May 20, 2019 at 5:51 PM
        • Sharath

          With this info I can’t able to diagnose what error it will be.
          Does the program shows any error?
          Does the thingspeak field show the time/date of updated data? It will be shown on last updated field.

          May 20, 2019 at 6:35 PM
  • PANKTI DESAI

    Can you please help in transferring data at faster rate to think speak,

    May 23, 2019 at 2:22 PM
    • Sharath

      The speed depends on internet speed, Thingspeak plans, etc. Check thingspeak paid plans for more details.

      May 23, 2019 at 4:41 PM
  • Kavyashree

    Sir how to upload mq 6 sensor data to thingsspeak cloud.

    June 6, 2019 at 5:54 AM
    • Sharath

      Same code instead of LDR, you have to connect MQ Sensor’s A0 Pin.

      June 6, 2019 at 1:17 PM
  • Kavyashree

    Sir how to upload gps data to thingsspeak cloud.

    June 6, 2019 at 5:55 AM
    • Sharath

      You have to store the GPS Data in a variable and use the ‘Numeric Display’ under widgets option on thingspeak. The value you write on this field and channel will be displayed in numeric.

      June 6, 2019 at 1:35 PM
  • Ilham

    how to add another sensor ? i want to use multiple sensor ? thank you before

    June 10, 2019 at 12:33 PM
  • PRAVEEN

    …….I READ ALL YOUR COMMENTS YOU WERE REPLYING EVERYONE WITH LOT OF PATIENCE SO I’M EAGERLY WAITING FOR YOUR REPLY ………….ALSO YOU CAN MESSAGE ME AT MY WHATSAPP SIR …..I CAN GIVE IT IF U NEED ……………. I’m doing a project using esp8266-01 project costs 15k with all setup i.e hydroponics .Actually i a had code for this without esp8266 interface so i want to add up a extra code to this to send data to thingspeak .Here im using lot of sensors but i think it is not possible to connect many sensors to it 1st version of ESP. I at least want to connect min of 2 sensors to this please say me the possibility of the code

    #include
    #define DS3231_I2C_ADDRESS 0x68

    #include “DHT.h”
    #define DHTPIN 8 // what digital pin we’re connected to
    #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

    #include

    DHT dht(DHTPIN, DHTTYPE);
    OneWire ds(12); // on pin 10 (a 4.7K resistor is necessary)
    BH1750 lightMeter;

    int relayIn1 = 2;
    int relayIn2 = 3;
    int relayIn3 = 4;
    int relayIn4 = 5;

    int flowSwitch1 = 9;
    int flowSwitch2 = 10;
    int flowSwitch3 = 11;

    int soil = A3;

    //Data variables

    int flowSwitch1Read = -1; //0 need water, 1 enough water;
    int flowSwitch2Read = -2; //0 need water, 1 enough water;
    int flowSwitch3Read = -3; //0 need water, 1 enough water;

    int lastMinute = -1;
    int nowMinute = -2;

    int nowHour = -1;

    float temperature = -1;
    float humidity = -1;

    int soilHumidity = -1;
    int soilHumidityLevel = 950;

    uint16_t lux = 1;

    void setup(){
    int status;
    Serial.begin(9600);
    pinMode(relayIn1, OUTPUT);
    pinMode(relayIn2, OUTPUT);
    pinMode(relayIn3, OUTPUT);
    pinMode(relayIn4, OUTPUT);

    pinMode(flowSwitch1, INPUT_PULLUP);
    pinMode(flowSwitch2, INPUT_PULLUP);
    pinMode(flowSwitch3, INPUT_PULLUP);

    digitalWrite(relayIn1, HIGH);
    digitalWrite(relayIn2, HIGH);
    digitalWrite(relayIn3, HIGH);
    digitalWrite(relayIn4, HIGH);

    pinMode(soil, INPUT);

    Wire.begin();

    dht.begin();

    lightMeter.begin();

    }

    void loop(){
    displayTime();

    delay(2000);

    if(lastMinute!=nowMinute){
    readSensorStatus();
    delay(2000);

    if (nowHour<7){
    //Night shift
    Serial.println("Night!");
    goto Night;
    } else {
    //Day shift
    Serial.println("Day!");
    if(luxsoilHumidityLevel){
    if(flowSwitch1Read==0){
    turnOnPump();
    }
    }

    lastMinute=nowMinute;

    }
    delay(1000);
    }
    }
    Night:;
    }

    void turnOnPump(){
    while(flowSwitch1Read==0){
    Serial.println(“Relay In 1 on”);
    digitalWrite(relayIn1, LOW);
    readSensorStatus();
    };
    Serial.println(“Relay In 1 off”);
    turnOffPump();
    }

    void turnOffPump(){
    digitalWrite(relayIn1, HIGH);
    }

    void turnOnLamp(){
    digitalWrite(relayIn4, LOW);
    }

    void turnOffLamp(){
    digitalWrite(relayIn4, HIGH);
    }

    void readSensorStatus(){
    lux = lightMeter.readLightLevel();
    Serial.print(“Light: “);
    Serial.print(lux);
    Serial.println(” lx”);
    flowSwitch1Read = digitalRead(flowSwitch1);
    Serial.print(“Water level in upper pipes: “);
    Serial.println(flowSwitch1Read);
    flowSwitch2Read = digitalRead(flowSwitch2);
    Serial.print(“Water in tank: “);
    Serial.println(flowSwitch2Read);
    flowSwitch3Read = digitalRead(flowSwitch3);
    Serial.print(“Minimum water in tank: “);
    Serial.println(flowSwitch3Read);
    //Serial.print(“Float Switch is “);
    readDHT();
    readWaterTemperature();
    soilHumidity = analogRead(soil);
    Serial.print(“Soil Humidity sensor value: “);
    Serial.println(soilHumidity);

    }

    // Convert normal decimal numbers to binary coded decimal
    byte decToBcd(byte val)
    {
    return( (val/10*16) + (val%10) );
    }
    // Convert binary coded decimal to normal decimal numbers
    byte bcdToDec(byte val)
    {
    return( (val/16*10) + (val%16) );
    }

    void readDS3231time(byte *second,
    byte *minute,
    byte *hour,
    byte *dayOfWeek,
    byte *dayOfMonth,
    byte *month,
    byte *year)
    {
    Wire.beginTransmission(DS3231_I2C_ADDRESS);
    Wire.write(0); // set DS3231 register pointer to 00h
    Wire.endTransmission();
    Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
    // request seven bytes of data from DS3231 starting from register 00h
    *second = bcdToDec(Wire.read() & 0x7f);
    *minute = bcdToDec(Wire.read());
    *hour = bcdToDec(Wire.read() & 0x3f);
    *dayOfWeek = bcdToDec(Wire.read());
    *dayOfMonth = bcdToDec(Wire.read());
    *month = bcdToDec(Wire.read());
    *year = bcdToDec(Wire.read());
    }

    void displayTime()
    {
    byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
    // retrieve data from DS3231
    readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,
    &year);

    nowMinute = minute;
    nowHour = hour;

    // send it to the serial monitor
    Serial.print(hour, DEC);
    // convert the byte variable to a decimal number when displayed
    Serial.print(“:”);
    if (minute<10)
    {
    Serial.print("0");
    }
    Serial.print(minute, DEC);
    Serial.print(":");
    if (second<10)
    {
    Serial.print("0");
    }
    Serial.print(second, DEC);
    Serial.print(" ");
    Serial.print(dayOfMonth, DEC);
    Serial.print("/");
    Serial.print(month, DEC);
    Serial.print("/");
    Serial.print(year, DEC);
    Serial.print(" Day of week: ");
    switch(dayOfWeek){
    case 1:
    Serial.println("Sunday");
    break;
    case 2:
    Serial.println("Monday");
    break;
    case 3:
    Serial.println("Tuesday");
    break;
    case 4:
    Serial.println("Wednesday");
    break;
    case 5:
    Serial.println("Thursday");
    break;
    case 6:
    Serial.println("Friday");
    break;
    case 7:
    Serial.println("Saturday");
    break;
    }
    }

    void readDHT(){
    humidity = dht.readHumidity();
    temperature = dht.readTemperature();

    if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
    } else {
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.print(" *C, Humidity: ");
    Serial.println(humidity);
    }

    }

    void readWaterTemperature(){
    byte i;
    byte present = 0;
    byte type_s;
    byte data[12];
    byte addr[8];
    float celsius, fahrenheit;

    if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(500);
    return;
    }

    Serial.print("ROM =");
    for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
    }

    if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
    }
    Serial.println();

    // the first ROM byte indicates which chip
    switch (addr[0]) {
    case 0x10:
    Serial.println(" Chip = DS18S20"); // or old DS1820
    type_s = 1;
    break;
    case 0x28:
    Serial.println(" Chip = DS18B20");
    type_s = 0;
    break;
    case 0x22:
    Serial.println(" Chip = DS1822");
    type_s = 0;
    break;
    default:
    Serial.println("Device is not a DS18x20 family device.");
    return;
    }

    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1); // start conversion, with parasite power on at the end

    delay(1000); // maybe 750ms is enough, maybe not
    // we might do a ds.depower() here, but the reset will take care of it.

    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE); // Read Scratchpad

    Serial.print(" Data = ");
    Serial.print(present, HEX);
    Serial.print(" ");
    for ( i = 0; i < 9; i++) { // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
    }
    Serial.print(" CRC=");
    Serial.print(OneWire::crc8(data, 8), HEX);
    Serial.println();

    // Convert the data to actual temperature
    // because the result is a 16 bit signed integer, it should
    // be stored to an "int16_t" type, which is always 16 bits
    // even when compiled on a 32 bit processor.
    int16_t raw = (data[1] << 8) | data[0];
    if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
    // "count remain" gives full 12 bit resolution
    raw = (raw & 0xFFF0) + 12 – data[6];
    }
    } else {
    byte cfg = (data[4] & 0x60);
    if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
    }
    celsius = (float)raw / 16.0;
    fahrenheit = celsius * 1.8 + 32.0;
    Serial.print(" Temperature = ");
    Serial.print(celsius);
    Serial.print(" Celsius, ");
    Serial.print(fahrenheit);
    Serial.println(" Fahrenheit");
    }

    this is the i want to over write…………….
    PLEASE HELP ME < THIS PROJECT IS GOING TO CREATE A LOT OF CHANGE IN MY CAREER

    June 20, 2019 at 8:12 PM
  • Kuldeep

    Is possible to make such program from where the Data can be read from the thingspeak and then that data can be used to control some hardware(like survo motor or led etc.)

    June 25, 2019 at 9:53 PM
    • Sharath

      Yes you can, We are using Write API in this example. Instead we need to use Read APIs to get the values and using a simple if..else conditions you can control it.

      You can use a seperate NodeMCU or the same for both and Read and Write operations. I think an in the File>Examples in Arduino IDE the read example code might be there. You can modify it according to that format.

      June 27, 2019 at 4:25 PM
  • Manju

    Sir plz send me ir sensor code for uploading could to things speak

    July 19, 2019 at 3:51 PM
    • Sharath

      Replace this line
       
      val = analogRead(LDRpin); //Read Analog values and Store in val variable
       
      with
       
      val = digitalReadRead(LDRpin); //Read Analog values and Store in val variable
       
      Initialize the pinmode as input in Setup Loop
       
      pinMode(LDRpin, INPUT); //LDR Pin is just a variable u can keep or change it to IR.

      July 19, 2019 at 7:00 PM
  • Sai Vishal Reddy

    hello sir, iam able to get the sensor data in the serial monitor but nothing is displayed in the thingspeak channel

    July 26, 2019 at 4:05 PM
    • Sharath

      Check the SSID and password in proper double quotes and Check the Channel ID and API Keys Once.

      July 26, 2019 at 4:13 PM
  • Chrissybing

    Hi Sharath

    Im trying to use an ADXL335 and upload the 3 fields x,y,z to thingspeak. I’ve added a bit of math conversion for the acceleraometer, but need help.

    Any help would be appreciated – Many thanks

    Code as follows:

    #include
    #define RX 10
    #define TX 11

    String AP = “***********”; // CHANGE ME
    String PASS = “***********”; // CHANGE ME
    String API = “************”; // CHANGE ME
    String HOST = “api.thingspeak.com”;
    String PORT = “80”;
    String field1 = “field1”;
    String field2 = “field2”;
    String field3 = “field3”;

    int countTrueCommand;
    int countTimeCommand;

    boolean found = false;

    int valSensor_x = A1;
    int valSensor_y = A2;
    int valSensor_z = A3; /* connect x_out of module to A1 of UNO board */
    SoftwareSerial esp8266(RX,TX);

    void setup() {
    Serial.begin(9600);
    esp8266.begin(115200);
    sendCommand(“AT”,5,”OK”);
    sendCommand(“AT+CWMODE=1″,5,”OK”);
    sendCommand(“AT+CWJAP=\””+ AP +”\”,\””+ PASS +”\””,20,”OK”);
    }
    void loop() {

    int x_adc_value, y_adc_value, z_adc_value;
    double x_g_value, y_g_value, z_g_value;

    x_adc_value = analogRead(A1); /* Digital value of voltage on x_out pin */
    y_adc_value = analogRead(A2); /* Digital value of voltage on y_out pin */
    z_adc_value = analogRead(A3); /* Digital value of voltage on z_out pin */

    x_g_value = ( ( ( (double)(x_adc_value * 5)/1024) – 1.65 ) / 0.330 ); /* Acceleration in x-direction in g units */
    y_g_value = ( ( ( (double)(y_adc_value * 5)/1024) – 1.65 ) / 0.330 ); /* Acceleration in y-direction in g units */
    z_g_value = ( ( ( (double)(z_adc_value * 5)/1024) – 1.80 ) / 0.330 ); /* Acceleration in z-direction in g units */

    String getData = “GET /update?api_key=”+ API +”&field1=” + x_g_value +”&field2=” + y_g_value +”&field3=” + z_g_value;

    sendCommand(“AT+CIPMUX=1″,5,”OK”);
    sendCommand(“AT+CIPSTART=0,\”TCP\”,\””+ HOST +”\”,”+ PORT,15,”OK”);
    sendCommand(“AT+CIPSEND=0,” +String(getData.length()+4),4,”>”);
    esp8266.println(getData);delay(1500);countTrueCommand++;
    sendCommand(“AT+CIPCLOSE=0″,5,”OK”);

    }
    int getSensorData(){
    return random(1000); // Replace with
    }

    void sendCommand(String command, int maxTime, char readReplay[]) {
    Serial.print(countTrueCommand);
    Serial.print(“. at command => “);
    Serial.print(command);
    Serial.print(” “);
    while(countTimeCommand < (maxTime*1))
    {
    esp8266.println(command);//at+cipsend
    if(esp8266.find(readReplay))//ok
    {
    found = true;
    break;
    }

    countTimeCommand++;
    }

    if(found == true)
    {
    Serial.println("OYI");
    countTrueCommand++;
    countTimeCommand = 0;
    }

    if(found == false)
    {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
    }

    found = false;
    }

    August 22, 2019 at 6:49 PM
  • sara

    will you please send the pulse sensor code using node mcu and connected to thingspeak

    September 22, 2019 at 4:31 PM
  • jawahar

    bro i need coding for level indicator using 3-IR sensor in nodemcu and thingspeak server

    September 27, 2019 at 9:51 AM
  • Tarun

    Hi…..
    I am interfacing the flame sensor with reading(CODE) bt i didn’t get the solution
    i used this code..
    void loop() {
    ThingSpeak.setField(1, number1);
    ThingSpeak.setField(2, number2);
    ThingSpeak.setField(3, number3);
    ThingSpeak.setField(4, number4);
    if(number1 > number2){
    myStatus = String(“field1 is greater than field2”);
    }
    else if(number1 < number2){ myStatus = String("field1 is less than field2"); }
    else{ myStatus = String("field1 equals field2"); }
    el int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
    if(x == 200){ Serial.println("Channel update successful."); }
    else{ Serial.println("Problem updating channel. HTTP error code " + String(x)); }
    }
    number1=rondom(0,100);
    number2 = random(0,100);
    number3 = random(0,100);
    number4 = random(0,100);

    delay(20000);
    }

    September 27, 2019 at 3:17 PM
    • Sharath

      Problems in the code:

      – Where is the setup loop in the code?
      – The code in the loop just do nothing as it doesn’t have this line
      ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); // or a similar function
      – It is just passing random number from 1 to 100 in all fields and quits without updating anywhere.
      – It also doesn’t print any compared values either.

      Also you didn’t mentioned what output you are trying to achieve.

      September 27, 2019 at 7:13 PM
  • grishma

    hello! sir! i have uploaded a code for gas sensor and neode mcu.But in things speak it doesnt show the graph. can you please guide? the code is here
    #include
    #include
    #include “MQ135.h”
    #include
    String apiKey = “1CUJEV41WNM7WHHP”; // Enter your Write API key from ThingSpeak
    const char *ssid = “Harrin”; // replace with your wifi ssid and wpa2 key
    const char *pass = “harrin20”;
    const char* server = “api.thingspeak.com”;
    WiFiClient client;
    unsigned long myChannelNumber = 876579;
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    #define VOLTAGE_MAX 5.0
    #define VOLTAGE_MAXCOUNTS 1023.0

    void setup() {
    Serial.begin(9600);
    delay(10);
    Serial.println(“Connecting to “);
    Serial.println(ssid);
    WiFi.begin(ssid, pass);
    ThingSpeak.begin(client);
    }

    void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // Convert the analog reading
    // On Arduino: 0 – 1023 maps to 0 – 5 volts
    // On ESP8266: 0 – 1023 maps to 0 – 1 volts
    // On Particle: 0 – 4095 maps to 0 – 3.3 volts
    float voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);
    Serial.print(voltage);
    Serial.println();

    delay(20000); // ThingSpeak will only accept updates every 15 seconds.
    }
    Thanks

    October 1, 2019 at 10:13 PM
    • Sharath

      ThingSpeak.writeField(myChannelNumber, 1,voltage, apiKey); //Update in ThingSpeak
       
      This line is missing in your code. It is the important line to update your data to thingspeak.
      The myChannelNumber, voltage and apiKey are the variables that holds data.
       
      In your case you are printing the ‘voltage’ variable in serial monitor, so that is the value you are updating in thingspeak. Hence that is mentioned in the ThingSpeak.writeField() function. The other two holds the channel number and keys that you defined before setup loop. The number ‘1’ mentioned in the function is the field that you are going to update.

      October 2, 2019 at 10:39 AM
      • Grishma

        That is done. Still not getting the graph.serial monitor shows the output but no output in Thingspeak. Above the graph in thingspeak 0 entries….plz help me further.

        October 2, 2019 at 6:42 PM
      • Grishma

        I done what you said. But no changes..still same situation. Serial monitor shows the values but nothing is displayed on Thingspeak.

        October 2, 2019 at 6:46 PM
        • Sharath

          Check if the SSID and Password is connected & Make sure it has internet connection
          Check the API Keys.There are two API Keys (Read API & Write API Keys). Check the correct type.
          Check your channel number.

          October 4, 2019 at 8:04 PM

Leave a Reply

Back to Blog