ESP32 temperature sensor tutorial: How to Stream real-time data to ThingSpeak
This is a simple IoT project that will send the temperature data from ESP-32 to thingspeak server. This will enable us to view the room temperature data from anywhere in
This is a simple IoT project that will send the temperature data from ESP-32 to thingspeak server. This will enable us to view the room temperature data from anywhere in this world through internet. The way we are going to do it is by using API provided by thingspeak.
What is API?
API stands for Application Programming Interface and it is the link between our software application and the website. If we want data from website to use in our application then we need the API. To understand API in better way lets assume that the website is a restaurant and our program/application is customer and the food is data. So to get the food, customer needs to give the dish name to the waiter from the menu card, along with that the waiter also notes the table number and gives that information to the kitchen staff. In similar way our program also requests data from website by posting the information like API key, topic parameter in the form of URL. This URL is API. If the API key matches the API key given to us by the website then the response is given by the website and the program gets the data.
In our project we are just posting the temperature data to Thingspeak server and not requesting any data. So first lets see how to get API from Thingspeak , publish data using API and then make the hardware connections.
What is ThingSpeak?
ThingSpeak is a IoT cloud platform service that allows us to visualize live data streams in the cloud. We can send data to ThingSpeak from our devices and create instant visualization of live data.
Components required
- ESP-32 dev board
- DHT-11 temperature and humidity sensor
- Jumper wire (M to M) – 3pcs
- USB micro cable
Getting API from Thingspeak and testing it
First we need to create an account on Thingspeak. Follow the below given steps-
Open the Thingspeak website then click on “sign in” in top right corner.
2. Click on “create one”.
3. Fill all the credentials and click on “continue”. Then you will get a verification link on your registered email ID . Click on that link. Set your password and your account will be created. Then you just login to Thingspeak.
4. After you logged in you will see this page. Click on “new channel”
- Give your channel a name, description, and Field1 name. As we are using only one field for temperature.
- New channel is now created. You will also see a blank chart displayed in private view. Click on API keys.
- Under API requests copy this URL. Through this URL we publish data to the channel field.
- Paste this URL in the address bar and assign the field parameter, any number or you can keep it zero. Then hit “enter”.
- Now open your channel , go to private view and view your chart. The field value will be updated to the chart and you will see a red horizontal line corresponding to your value.
If the value is not updated, try reloading the page.
This indicates that the API is working and can be used in our program. Now that we have tested the API, lets make the hardware connections for the project.
Circuit diagram
Make the connections as per below given circuit diagram
The DHT-11 temperature sensor has 3 pins, ground, vcc and data. It sends calibrated temperature output in degree Celsius on the data line. The data pin is connected on GPIO 5 of ESP-32. It’s temperature range is from 0 to 50 degree Celsius. It’s operating voltage is 3V to 5V. So we can directly give it 3.3V from ESP-32 and get the room temperature readings.
Once the connections are done. Connect the ESP-32 to COM port through USB cable and open the Arduino IDE.
Install the DHT-11 library
Open library manager and search for “DHT11” and install the “DHT sensor library by Adafruit”
The DHT-11 sensor will now work with our program as it’s library is installed.
Go to tools and select the board “ESP32 Dev Module” and select the proper com port according to the device manager. If you are beginner to ESP boards and want ESP boards to be added in Arduino IDE then refer this beginners guide blog.
Now we are done with all setup. Before uploading the code, modify it according to your WiFi ssid and password. Also assign your “write API key” to the apiKey parameter which you will get from your Thingspeak channel under API keys.
Upload the below given code. Open the serial monitor to see the status. Set baud rate to "115200". As soon as it will connect to WiFi, It will start publishing room temperature after interval of 10 seconds. You can change this interval by changing the delay in the “void loop()”.
If the value is updated you will get response code “-1” if you got “400” that means there is error.
Code
#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
#define DHTPIN 5
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "your WiFi ssid";
const char* password = "Your WiFi password";
// Domain Name with full URL Path for HTTP POST Request
const char* serverName = "http://api.thingspeak.com/update";
// write API Key provided by thingspeak
String apiKey = "your write API key";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
dht.begin();
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
delay(10000); // wait for 10 seconds
//float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Your Domain name with URL path or IP address with path
http.begin(client, serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
String httpRequestData = "api_key=" + apiKey + "&field1=" + String(t);
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
/*
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
// JSON data to send with HTTP POST
String httpRequestData = "{\"api_key\":\"" + apiKey + "\",\"field1\":\"" + String(random(40)) + "\"}";
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);*/
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
}
Conclusion
In this way we created a simple IoT project which sends temperature sensor data from ESP32 to ThingSpeak server. If you have any doubt regarding any part of this blog, feel free to comment. Our team will be there to assist you.
For more interesting projects check out our YouTube channel.