Get Started-nodemcu-7-thingspeak
|

ThingSpeak with NodeMCU: Step-by-Step Guide

IoT (Internet of Things) is transforming the way we interact with devices. One of the most effective ways to monitor sensor data remotely is by sending it to a cloud platform like ThingSpeak, where we can visualize it in real-time.

This tutorial will use a NodeMCU ESP8266 to send temperature, humidity, and distance measurements from a DHT11 sensor and an HC-SR04 ultrasonic sensor to ThingSpeak. We will also display the data in real-time on ThingSpeak’s dashboard.

What is ThingSpeak?

ThingSpeak is an IoT analytics cloud platform that enables users to collect and store sensor data, analyze data using MATLAB, create real-time visualizations, and set up alerts and notifications.

Now, let’s start setting up the hardware and coding our NodeMCU.

Components Required

  • NodeMCU ESP8266
  • DHT11 Temperature & Humidity Sensor(How to use)
  • HC-SR04 Ultrasonic Sensor
  • Jumper wires
  • Breadboard

Circuit Diagram

Connect the components as follows:

Nodemcu-with-dht11-hcsr04-sensor

Setting Up ThingSpeak

  1. Go to ThingSpeak and create an account.
  2. Click on “New Channel” and name it (e.g., “Sensor Data”).
  3. Add three fields:
    • Field 1: Temperature (°C)
    • Field 2: Humidity (%)
    • Field 3: Distance (cm)
  4. Click Save Channel.
  5. Go to the API Keys tab and copy your Write API Key (you’ll use this in the code).
  6. Note down your Channel ID as well.

Programming the NodeMCU

Code Example:

/*
 *  Project: Real-Time Sensor Data Logging to ThingSpeak with NodeMCU
 *  Author: Manuja Yasanga
 *  Website: https://mechatronicslearning.com
 *  
 *  Description:
 *  This code reads temperature and humidity data from a DHT11 sensor and distance 
 *  measurements from an HC-SR04 ultrasonic sensor using a NodeMCU (ESP8266). 
 *  The data is then uploaded to ThingSpeak for real-time visualization.
 *  
 *  License:
 *  This is open-source code provided by mechatronicslearning.com.
 *  You can use, modify, and distribute it for learning and project purposes.
 *  
 *  More NodeMCU tutorials available at: https://mechatronicslearning.com
 */


#include <ESP8266WiFi.h>
#include <DHT.h>
#include <ThingSpeak.h>

#define DHTPIN 2        // DHT11 data pin connected to GPIO2 (D4)
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

#define TRIGPIN 14       // HC-SR04 Trig pin connected to GPI14 (D5)
#define ECHOPIN 12       // HC-SR04 Echo pin connected to GPI12 (D6)

const char* ssid = "YOUR_SSID";          // Replace with your WiFi SSID
const char* password = "YOUR_PASSWORD";  // Replace with your WiFi Password
unsigned long myChannelNumber = YOUR_CHANNEL_ID; //Replace with your channel ID
const char* myWriteAPIKey = "YOUR_WRITE_API_KEY"; //Replace with your write api key

WiFiClient client;

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    
    Serial.print("Connecting to WiFi");
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }
    Serial.println("\nConnected to WiFi");

    ThingSpeak.begin(client);
    dht.begin();
    pinMode(TRIGPIN, OUTPUT);
    pinMode(ECHOPIN, INPUT);
}

void loop() {
    // Read DHT11 data
    float temp = dht.readTemperature();
    float hum = dht.readHumidity();
    
    // Read HC-SR04 data
    digitalWrite(TRIGPIN, LOW);
    delayMicroseconds(2);
    digitalWrite(TRIGPIN, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIGPIN, LOW);
    float duration = pulseIn(ECHOPIN, HIGH);
    float distance = (duration * 0.0343) / 2; // Convert to cm
    
    // Print values
    Serial.print("Temperature: "); Serial.print(temp); Serial.println(" °C");
    Serial.print("Humidity: "); Serial.print(hum); Serial.println(" %");
    Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm");
    
    // Upload to ThingSpeak
    ThingSpeak.setField(1, temp);
    ThingSpeak.setField(2, hum);
    ThingSpeak.setField(3, distance);
    
    int response = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
    if (response == 200) {
        Serial.println("Data uploaded successfully");
    } else {
        Serial.println("Error uploading data");
    }
    
    delay(15000); // ThingSpeak allows updates every 15 seconds
}

How the Code Works

This code reads temperature and humidity from a DHT11 sensor and distance from an HC-SR04 ultrasonic sensor, then sends the data to ThingSpeak for real-time visualization using a NodeMCU (ESP8266). Below is a breakdown of how the code works:

1. Include Required Libraries

#include <ESP8266WiFi.h>
#include <DHT.h>
#include <ThingSpeak.h>
  • ESP8266WiFi.h → Allows the NodeMCU to connect to WiFi.
  • DHT.h → Enables communication with the DHT11 sensor.
  • ThingSpeak.h → Enables sending data to ThingSpeak.

2. Define Sensor Pins

#define DHTPIN D4        // DHT11 data pin connected to GPIO2 (D4)
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

#define TRIGPIN D1       // HC-SR04 Trig pin connected to GPIO5 (D1)
#define ECHOPIN D2       // HC-SR04 Echo pin connected to GPIO4 (D2)
  • Defines DHT11 sensor pin (D4).
  • Defines HC-SR04 ultrasonic sensor pins (D1 for Trig, D2 for Echo).
  • Creates a DHT object to manage temperature and humidity readings.

3. WiFi and ThingSpeak Setup

const char* ssid = "your_WiFi_name";          // Replace with your WiFi SSID
const char* password = "your_WiFi_password";  // Replace with your WiFi Password
unsigned long myChannelNumber = YOUR_CHANNEL_ID; //Replace with your Channel ID
const char* myWriteAPIKey = "YOUR_WRITE_API_KEY"; //Replace with your write API key

WiFiClient client;
  • Stores WiFi credentials (ssid and password).
  • Stores ThingSpeak channel ID and Write API key.
  • Creates a WiFiClient object to communicate with ThingSpeak.

4. Setup Function (setup())

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    
    Serial.print("Connecting to WiFi");
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }
    Serial.println("\nConnected to WiFi");

    ThingSpeak.begin(client);
    dht.begin();
    pinMode(TRIGPIN, OUTPUT);
    pinMode(ECHOPIN, INPUT);
}
  • Starts serial communication (Serial.begin(115200)) for debugging.
  • Connects to WiFi (WiFi.begin(ssid, password)) and waits until it’s connected.
  • Initializes ThingSpeak (ThingSpeak.begin(client)).
  • Initializes the DHT11 sensor (dht.begin()).
  • Configures HC-SR04 pins (pinMode(TRIGPIN, OUTPUT); pinMode(ECHOPIN, INPUT);).

5. Main Loop (loop())

5.1. Read Data from DHT11 Sensor
float temp = dht.readTemperature();
float hum = dht.readHumidity();
  • Reads temperature and humidity from the DHT11 sensor.
5.2. Read Distance from HC-SR04 Sensor
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
float duration = pulseIn(ECHOPIN, HIGH);
float distance = (duration * 0.0343) / 2; // Convert to cm
  • Sends a pulse from the Trig pin to the HC-SR04 sensor.
  • Measures the time taken for the pulse to return using pulseIn().
  • Converts duration into distance in centimeters (distance = (duration * 0.0343) / 2).
5.3. Print Sensor Values to Serial Monitor
Serial.print("Temperature: "); Serial.print(temp); Serial.println(" °C");
Serial.print("Humidity: "); Serial.print(hum); Serial.println(" %");
Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm");
  • Displays the sensor readings in the Serial Monitor.
5.4. Send Data to ThingSpeak
ThingSpeak.setField(1, temp);
ThingSpeak.setField(2, hum);
ThingSpeak.setField(3, distance);
  • Stores temperature in Field 1, humidity in Field 2, and distance in Field 3.
5.5. Upload Data and Check Response
int response = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (response == 200) {
    Serial.println("Data uploaded successfully");
} else {
    Serial.println("Error uploading data");
}
  • Sends data to ThingSpeak and checks if the upload was successful (response code 200).
5.6. Wait for 15 Seconds
delay(15000); // ThingSpeak allows updates every 15 seconds
  • ThingSpeak allows updates every 15 seconds, so the delay(15000) ensures that the next update happens after 15 seconds.

Visualizing Data on ThingSpeak

  1. Go to your ThingSpeak Channel Dashboard.
  2. Click on “Private View” to see the live data graphs.
  3. For a better view, navigate to “Public View” and add widgets like line graphs for real-time visualization.
Thingspeak-dashboard-data-visualization

In this tutorial, we successfully configured a NodeMCU ESP8266 with DHT11 and HC-SR04 sensors, transmitted real-time data to ThingSpeak, and visualized the information using its live graphs. This demonstration highlights hardware integration with cloud-based analytics and sets the stage for future IoT projects. We hope this guide is a valuable resource for continued exploration in this field.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *