ESP32 ThingSpeak Tutorial: Send Sensor Data to the Cloud
Send sensor data from an ESP32 to ThingSpeak: channel and Write API Key, the 15-second limit, DHT22 code, deep sleep, phone charts, MATLAB and Blynk compared.
The ESP32 and ThingSpeak pair is the quickest way to put sensor data on the internet and watch it on ready-made charts. The ESP32 sends the temperature, humidity or light level it measures to the ThingSpeak server with a single HTTP request; the server stores every value with a timestamp, and you can see line charts from anywhere in the world without writing a single web page. ThingSpeak is the IoT platform of MathWorks, the maker of MATLAB, and small non-commercial projects can use it with a free account.
In this guide you'll first understand how ThingSpeak works (channels, fields, API keys) and then work through the 15-second rule of the free account with real numbers. After that we'll write ESP32 code with a DHT22 sensor, once with a plain HTTP request and no extra library, and once with the official ThingSpeak library and deep sleep. You'll also find how to watch the charts on your phone, read the data back, analyse it with MATLAB, a Raspberry Pi Pico W version and a ThingSpeak vs Blynk vs Google Sheets comparison.

What is ThingSpeak and how does it work?
Everything in ThingSpeak revolves around a channel. Think of a channel as a table whose columns you define: it holds up to 8 data fields (field1–field8), a status text and optional location data. Each time the ESP32 sends data, a new row is added; this row is called an entry, and the server numbers it and adds the timestamp itself. To send data, you only need to call a simple address that contains the channel's secret Write API Key: api.thingspeak.com/update?api_key=KEY&field1=23.5. The server returns the number of the new entry; if the entry is rejected, the reply is 0.
| Concept | What it does | Example in this guide |
|---|---|---|
| Channel | A table that collects the data of one device or project | Living Room Climate |
| Field (1–8) | Each measurement column in the channel; every field gets its own chart | field1 temperature, field2 humidity, field3 Wi-Fi signal |
| Channel ID | The channel's numeric ID; needed for reading and for the library | 1234567 |
| Write API Key | A 16-character secret key that allows writing to the channel | WRITE_API_KEY |
| Read API Key | The key for reading data from a private channel | Reading on your phone and other devices |
| Entry | The row of values sent in one update; it has a number and a time | A new entry every 20 seconds |
| Status | A short text that can be attached to an entry | "Hot" or "Normal" |
Free account limits: the 15-second rule
With a free ThingSpeak account you can write to a channel at most once every 15 seconds; requests that come faster are rejected and the reply is 0. The second limit is the yearly message count: about 3 million messages a year, or roughly 8,200 per day on average. Let's do the maths: writing to one channel every 15 seconds means 86,400 / 15 = 5,760 messages a day, which keeps you below the limit. Feed two channels at the same rate and you reach 11,520 messages a day and use up your yearly allowance in about eight and a half months. That's why an interval between 20 seconds and 5 minutes is both enough and safe for home and greenhouse monitoring. Writing several readings to different fields in the same request also counts as a single message.
| Limit | Free account | What it means in practice |
|---|---|---|
| Update interval | At least 15 seconds per channel | Use 20 seconds in your code to leave room for network delays |
| Messages | About 3 million a year (around 8,200 a day on average) | One channel at 15-second intervals uses 5,760 messages a day |
| Number of channels | 4 channels | Open one channel per room or device |
| Fields per channel | 8 fields | Temperature, humidity, pressure, battery voltage and more go in one request |
| Terms of use | Non-commercial projects | A product or service needs a paid licence |
Creating a ThingSpeak channel step by step
- Sign in at thingspeak.mathworks.com with a MathWorks account; if you don't have one, you can create it for free with your email.
- In the top menu go to Channels > My Channels > New Channel.
- Give the channel a name (e.g. Living Room Climate), tick Field 1 and name it Temperature, name Field 2 Humidity and Field 3 RSSI.
- Save the channel with the Save Channel button at the bottom of the page and note the Channel ID shown at the top.
- Open the API Keys tab and copy the Write API Key.
- Test it in the browser before writing any code: type api.thingspeak.com/update?api_key=YOURKEY&field1=21 into the address bar. If you see 1, the channel works.
- On the Private View tab, watch the first point appear on the Field 1 chart.
Wiring: DHT22 sensor and ESP32
| DHT22 pin | ESP32 | Raspberry Pi Pico W | Note |
|---|---|---|---|
| VCC (+) | 3V3 | 3V3 (OUT) | Works on 3.3 V |
| DATA (OUT) | GPIO 4 | GP15 | On a bare sensor add a 10 kΩ pull-up between DATA and VCC; modules already have it |
| NC | Not connected | Not connected | Only present on the bare 4-pin sensor |
| GND (−) | GND | GND | Common ground |
Because the Arduino Uno has no Wi-Fi, we use an ESP32 or a Pico W for this project. The DHT22 can deliver a reading every two seconds, so a 20-second sending interval doesn't strain the sensor either. For sensor details and troubleshooting see the DHT11 and DHT22 guide, and to look up the board pins quickly use the pinout tool.
ESP32 ThingSpeak code (over HTTP, no extra library)
The first sketch only uses the WiFi and HTTPClient libraries that come with the ESP32 core, plus Adafruit's DHT sensor library for the sensor. Just fill in the three constants at the top with your Wi-Fi name, password and Write API Key. Every 20 seconds the code measures temperature, humidity and Wi-Fi signal strength, sends all three to three separate fields in one request and prints the server's reply to the Serial Monitor.
1// ESP32 + DHT22 -> ThingSpeak (HTTP GET, kütüphanesiz / no extra library)
2#include <WiFi.h>
3#include <HTTPClient.h>
4#include <DHT.h> // "DHT sensor library" (Adafruit)
5
6const char* WIFI_SSID = "WIFI_ADIN"; // Wi-Fi adın / your Wi-Fi name
7const char* WIFI_PASS = "WIFI_SIFRESI"; // Wi-Fi şifren / your Wi-Fi password
8const char* WRITE_KEY = "YAZMA_API_ANAHTARI"; // kanalın Write API Key'i / channel Write API Key
9
10const int DHT_PIN = 4; // DHT22 veri pini / DHT22 data pin
11const unsigned long INTERVAL_MS = 20000; // 15 sn sınırının üstünde kal / stay above the 15 s limit
12
13DHT dht(DHT_PIN, DHT22);
14unsigned long lastSend = 0;
15
16void connectWiFi() {
17 WiFi.begin(WIFI_SSID, WIFI_PASS);
18 Serial.print("Wi-Fi");
19 unsigned long start = millis();
20 while (WiFi.status() != WL_CONNECTED && millis() - start < 15000) {
21 delay(500);
22 Serial.print(".");
23 }
24 Serial.println(WiFi.status() == WL_CONNECTED ? " bagli / connected" : " baglanamadi / failed");
25}
26
27void setup() {
28 Serial.begin(115200);
29 dht.begin();
30 WiFi.mode(WIFI_STA);
31 connectWiFi();
32}
33
34void loop() {
35 if (lastSend != 0 && millis() - lastSend < INTERVAL_MS) return; // zamanı gelmedi / not yet
36 lastSend = millis();
37
38 float t = dht.readTemperature(); // °C
39 float h = dht.readHumidity(); // %
40 if (isnan(t) || isnan(h)) {
41 Serial.println("DHT22 okunamadi / read failed");
42 return;
43 }
44 if (WiFi.status() != WL_CONNECTED) connectWiFi();
45 if (WiFi.status() != WL_CONNECTED) return;
46
47 // field1 = sıcaklık, field2 = nem, field3 = Wi-Fi sinyali / temperature, humidity, Wi-Fi signal
48 String url = String("http://api.thingspeak.com/update?api_key=") + WRITE_KEY +
49 "&field1=" + String(t, 1) +
50 "&field2=" + String(h, 1) +
51 "&field3=" + String(WiFi.RSSI());
52
53 HTTPClient http;
54 http.begin(url);
55 int code = http.GET(); // 200 = sunucu cevap verdi / server answered
56 String body = http.getString(); // kayıt numarası, 0 = kabul edilmedi / entry id, 0 = rejected
57 http.end();
58
59 Serial.printf("T=%.1f C H=%.1f %% HTTP %d kayit/entry %s\n", t, h, code, body.c_str());
60 if (code == 200 && body == "0") Serial.println("Reddedildi: anahtar ya da 15 sn / rejected: key or 15 s");
61}| Code part | What it does |
|---|---|
| INTERVAL_MS = 20000 | Waits 20 seconds between updates, so it never hits the 15-second limit |
| Timing with millis() | No delay(), so loop() is free to do other work |
| field1, field2, field3 | Writes three values to three fields in one request; counts as one message |
| String(t, 1) | Turns the temperature into text with one decimal place (e.g. 23.4) |
| http.GET() | Sends the request; 200 means the server answered |
| http.getString() | The entry number returned by the server; 0 means the entry was rejected |
| WiFi.RSSI() | Wi-Fi signal strength (dBm); worse than -70 and you can expect dropouts |
Battery-friendly updates with the ThingSpeak library and deep sleep
If you install the ThingSpeak library (MathWorks) from the Arduino IDE Library Manager, you don't have to build addresses by hand: fill the fields with setField() and send them all at once with writeFields(). The function returns 200 on success and a meaningful error code otherwise. The sketch below combines this library with deep sleep: the ESP32 wakes up, measures, sends and sleeps for 10 minutes. Because the board is only awake for a few seconds per cycle, you can build a sensor that runs on batteries for weeks; actual consumption still depends on your board's regulator and USB chip.
1// ESP32 + DHT22 -> ThingSpeak kütüphanesi + derin uyku / ThingSpeak library + deep sleep
2#include <WiFi.h>
3#include <ThingSpeak.h> // "ThingSpeak" (MathWorks)
4#include <DHT.h>
5
6const char* WIFI_SSID = "WIFI_ADIN";
7const char* WIFI_PASS = "WIFI_SIFRESI";
8const unsigned long CHANNEL_ID = 1234567; // kanal numaran / your channel ID
9const char* WRITE_KEY = "YAZMA_API_ANAHTARI"; // Write API Key
10const uint64_t SLEEP_US = 10ULL * 60ULL * 1000000ULL; // 10 dakika uyku / sleep 10 minutes
11
12WiFiClient client;
13DHT dht(4, DHT22);
14
15void goToSleep() {
16 WiFi.disconnect(true); // Wi-Fi'yi kapat / turn Wi-Fi off
17 esp_sleep_enable_timer_wakeup(SLEEP_US);
18 esp_deep_sleep_start(); // uyanınca setup() baştan çalışır / setup() runs again on wake
19}
20
21void setup() {
22 Serial.begin(115200);
23 dht.begin();
24 delay(2000); // DHT22 ilk ölçüm için hazırlansın / let the DHT22 settle
25 float t = dht.readTemperature();
26 float h = dht.readHumidity();
27
28 WiFi.mode(WIFI_STA);
29 WiFi.begin(WIFI_SSID, WIFI_PASS);
30 unsigned long start = millis();
31 while (WiFi.status() != WL_CONNECTED && millis() - start < 15000) delay(200);
32
33 if (WiFi.status() == WL_CONNECTED && !isnan(t) && !isnan(h)) {
34 ThingSpeak.begin(client);
35 ThingSpeak.setField(1, t); // field1: sıcaklık / temperature
36 ThingSpeak.setField(2, h); // field2: nem / humidity
37 ThingSpeak.setStatus(t > 30 ? "Sicak / Hot" : "Normal");
38 int result = ThingSpeak.writeFields(CHANNEL_ID, WRITE_KEY);
39 Serial.printf("ThingSpeak cevap / reply: %d\n", result); // 200 = başarılı / success
40 } else {
41 Serial.println("Wi-Fi ya da sensor hatasi / Wi-Fi or sensor error");
42 }
43 goToSleep();
44}
45
46void loop() {}| writeFields() result | Meaning | What to do |
|---|---|---|
| 200 | Entry added | All good |
| 400 / 404 | Wrong API key or server address | Copy the Write API Key again |
| -210 | setField() was not called before writeFields() | Fill at least one field |
| -301 | Could not connect to ThingSpeak | Check Wi-Fi and the internet connection |
| -304 | The server didn't answer in time | Improve the signal and try again shortly |
| -401 | Entry not added; most likely the 15-second limit | Make the interval longer |
Watching the charts on your phone and reading data back
You can open your channel's charts in your phone's browser and add a shortcut to the home screen. If you make the channel public under Sharing in the channel settings, the Public View page is visible without signing in; if you want to keep it private, you need to sign in with your MathWorks account. On Google Play and the App Store there are also third-party apps that show ThingSpeak channels as charts and home-screen widgets; they usually only ask for the Channel ID and Read API Key. To read the data from another device or your own app, use the addresses below.
| Request | Address | Returns |
|---|---|---|
| Last value of a field | api.thingspeak.com/channels/CHANNEL_ID/fields/1/last.txt | Just the number (e.g. 23.4) |
| Last 10 entries | api.thingspeak.com/channels/CHANNEL_ID/feeds.json?results=10 | JSON with all fields |
| History of one field | api.thingspeak.com/channels/CHANNEL_ID/fields/2.json?results=100 | The last 100 values of that field |
| Private channel | Add &api_key=READ_KEY to the end of the address | No reply without the Read API Key |
Reading with the library is even shorter: ThingSpeak.readFloatField(CHANNEL_ID, 1, READ_KEY) returns the last value of a field as a number. That way you can show the temperature measured by the ESP32 in the garden on the OLED display of another ESP32 in the living room. If you want to parse the JSON reply, the ArduinoJson guide makes it easy.
Visualisation and analysis with MATLAB
What sets ThingSpeak apart from other IoT dashboards is that you can run MATLAB in the browser without installing anything. You create a new visualisation from Apps > MATLAB Visualizations; the thingSpeakRead function pulls your channel data, you draw the chart you want with familiar commands such as plot, and the result appears as a new window on your channel page. MATLAB Analysis performs calculations and writes the result to another channel with thingSpeakWrite; TimeControl runs that analysis at fixed intervals, and React runs it automatically when a field crosses a threshold.
- Show temperature and humidity on the same chart with two separate axes.
- Print the minimum, maximum and average temperature of the last 24 hours in a single window.
- Calculate the dew point from temperature and humidity and write it to a separate channel every hour.
- Filter sensor noise with a moving average and draw a smoothed curve.
- When the temperature goes above 30 °C, use React to fire a ThingHTTP request that notifies another service.
ThingSpeak with the Raspberry Pi Pico W (MicroPython)
You can do the same with a Raspberry Pi Pico W. The Pico W build of MicroPython ships with the network module for Wi-Fi, urequests for HTTP and dht for the sensor. Connect the DHT22 data pin to GP15 and save the code to the board as main.py with Thonny; on every power-up the board connects to Wi-Fi and sends a reading every 20 seconds. If you're new to MicroPython, take a look at MicroPython basics first.
1# Raspberry Pi Pico W + DHT22 -> ThingSpeak (MicroPython)
2import network, time, urequests, dht
3from machine import Pin
4
5SSID = "WIFI_ADIN" # Wi-Fi adın / your Wi-Fi name
6PASSWORD = "WIFI_SIFRESI" # Wi-Fi şifren / your Wi-Fi password
7WRITE_KEY = "YAZMA_API_ANAHTARI" # Write API Key
8
9sensor = dht.DHT22(Pin(15)) # DHT22 veri -> GP15 / data -> GP15
10
11wlan = network.WLAN(network.STA_IF)
12wlan.active(True)
13wlan.connect(SSID, PASSWORD)
14while not wlan.isconnected():
15 time.sleep(0.5)
16print("Bagli / connected:", wlan.ifconfig()[0])
17
18while True:
19 try:
20 sensor.measure()
21 t = sensor.temperature()
22 h = sensor.humidity()
23 url = "http://api.thingspeak.com/update?api_key={}&field1={:.1f}&field2={:.1f}".format(WRITE_KEY, t, h)
24 r = urequests.get(url)
25 print("T={:.1f} H={:.1f} kayit / entry: {}".format(t, h, r.text)) # 0 = reddedildi / rejected
26 r.close()
27 except Exception as e:
28 print("Hata / error:", e)
29 time.sleep(20) # 15 sn sınırının üstü / above the 15 s limitThingSpeak vs Blynk vs Google Sheets
| Feature | ThingSpeak | Blynk | Google Sheets |
|---|---|---|---|
| Best at | Data logging, charts and analysis | Phone control dashboards | Storing and sharing data as a table |
| Setup | Create a channel, copy the key | Set up a template, datastreams and a dashboard | Write Apps Script and deploy it as a web app |
| Charts | Automatic, for every field | With a chart widget on the dashboard | With Sheets charts, by hand |
| Controlling the device | Limited (reading and TalkBack) | Very easy, real-time and two-way | Not suitable |
| Shortest interval (free) | 15 seconds | Depends on the plan's message limit | 1 minute or more in practice |
| Analysis | MATLAB, in the browser | Almost none | Formulas and pivot tables |
| Phone | Browser or third-party app | Official app and notifications | Sheets app |
In short: if you want to log data and study it with charts and analysis, choose ThingSpeak; if you want to switch relays from your phone, choose Blynk; if you want to archive readings as a table and share them, choose Google Sheets. If you have a computer or Raspberry Pi running at home all the time, MQTT and Home Assistant can replace all of them.
ESP32 ThingSpeak project ideas
- Balcony weather station: track temperature, humidity and pressure on daily ThingSpeak charts (ESP32 BME280 weather station).
- Plant monitor: log soil moisture and learn your watering habits from the chart (soil moisture sensor).
- Water tank level: see how full the tank is from anywhere and calculate usage with MATLAB (water tank level meter).
- Household electricity: write power and energy once a minute (PZEM-004T energy meter).
- A cabin or allotment with no Wi-Fi: send the data over GPRS (TTGO T-Call ESP32 SIM800L).
Common mistakes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Reply is HTTP 200 but the entry is 0 | Wrong key or 15 seconds not yet passed | Copy the Write API Key again and set the interval to 20 seconds |
| Negative HTTP code (-1, -11) | Weak Wi-Fi or the server can't be reached | Check the signal (RSSI) and keep the reconnect code |
| No points on the chart, but the Serial Monitor shows entry numbers | You're writing to another channel or another field | Check the Channel ID and the field numbers |
| The chart only shows the last few points | The chart is set to show only a few results | Use the chart's pencil icon to raise Results or Days |
| Temperature is always nan | DHT22 wire or pull-up resistor missing | Connect DATA to GPIO 4 and add 10 kΩ on a bare sensor |
| No data at all after deep sleep | Wi-Fi can't connect within 15 seconds | Move closer to the router or extend the connection timeout |
| After a while, a warning that your messages are used up | Interval too short or too many channels | Make the interval longer and combine values in one request |
An easier way: BlueGrays IoT
ThingSpeak is a strong platform for logging data over long periods and analysing it with MATLAB. If you just want to switch a relay from your phone or watch a sensor value, BlueGrays IoT does it with ready templates, without creating a channel, setting up fields and copying the Write API Key into your code. Ohmi prepares the code with the device key for you. All you need is an ESP32 or Raspberry Pi Pico W and 2.4 GHz Wi-Fi, and your first device is free. For the full setup, see the guide to controlling an ESP32 from your phone.
If you want to test the sensors and the ESP32's Wi-Fi connection one by one before sending anything to ThingSpeak, the BlueGrays app has ESP32 projects such as DHT22, Wi-Fi connection and weather API, each with a step-by-step circuit diagram and ready-made code; adding the ThingSpeak lines on top of that takes just a few minutes.
Frequently asked questions
Is ThingSpeak free?
Yes, there's a free account for small non-commercial projects. With it you can create 4 channels, send about 3 million messages a year and write to each channel at most once every 15 seconds. Commercial use requires a paid licence.
How often can I send data to ThingSpeak?
On a free account you can write to the same channel at least 15 seconds apart; faster requests are rejected with a reply of 0. To leave room for network delays, using an interval of 20 seconds or more in your code is the safest choice.
Where do I find the ThingSpeak Write API Key?
Open your channel and go to the API Keys tab; the Write API Key is in the top box. The same page also shows the Read API Key for private channels. If the key leaks, you can generate a new one on the same tab.
Why isn't my ESP32 sending data to ThingSpeak?
The most common causes are a wrong Write API Key, hitting the 15-second limit and a weak Wi-Fi signal. If the Serial Monitor shows HTTP 200 and entry 0, the problem is the key or the timing; if you see a negative code, the ESP32 can't reach the server.
Can an ESP32 read data from ThingSpeak?
Yes. You can read the last value of a field from the last.txt address or with the library's readFloatField() function. That way you can show a value measured by one ESP32 on another ESP32's display or handle simple control tasks.
Which is better, ThingSpeak or Blynk?
It depends on your goal. For data logging, automatic charts and MATLAB analysis, ThingSpeak is the better fit; for controlling relays and LEDs with buttons on your phone and instant notifications, Blynk is better. You can also use both on the same ESP32.
Projects to build after reading this
See all projects
LED Blink with ESP32
Teaches basic GPIO output usage with ESP32. We achieve a blinking effect by turning an LED on and off from a digital pin. ESP32 version of the classic blink project on Arduino UNO; the basic blink commands in the Arduino environment are the same, but the ESP32's pin layout and 3.3 V GPIO levels differ from those of the Arduino UNO.

Reading Light Intensity with the ESP32 LDR Module
Real-time monitoring of the LDR module's raw ADC value and relative light percentage calculated from dark and light reference values in the Serial Monitor. This percentage is not a lux measurement. Teaches the module’s calibration logic. It is ideal to complete this before Project 10, as it is used to determine the threshold value.

ESP32 DHT22 Temperature and Humidity (with LCD Display)
This project measures ambient temperature and humidity using a DHT22 sensor and displays the data in real time on a 16x2 I2C LCD. Data is read from the sensor using the one-wire protocol via the Adafruit DHT library. This project serves as the foundation for IoT weather stations, smart home automation, or environmental monitoring systems in greenhouses. Communication with the DHT22 is established via the ESP32's GPIO 4 pin.

ESP32 Wi-Fi STA Connection (with LCD Screen)
In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

ESP32 HTTPClient + Weather API (with LCD Screen)
In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. The JSON response is parsed with ArduinoJson v7, and the city, temperature, humidity, weather and wind are shown on an I2C LCD. wttr.in needs no API key; just type the name of any city.

ESP32 HTTPClient + Weather API (with SSD1306 OLED Display)
In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. Unlike the I2C LCD version, it uses an SSD1306 OLED (128×64) display, with large text and vector icons for a richer look. Seven weather icons (sunny, rainy, snowy and more) are drawn on the fly, with no bitmap files.

ESP32 Deep Sleep — Battery Saving (OLED + RTC RAM Counter)
The ESP32's Deep Sleep mode shuts down the CPU and most peripherals, cutting current draw to about 10µA, which is vital for battery-powered IoT devices. This project uses three wake-up sources: a timer (15 s), an external pin (EXT0, the button on GPIO 33) and a touch pin (T0/GPIO 4). Counters marked with RTC_DATA_ATTR survive deep sleep.

ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)
Build a timed temperature and humidity logger with the ESP32! A DHT22 sensor reads temperature and humidity once a minute, and each reading is saved to a microSD card in CSV format with a real-time stamp from the DS1307 RTC module. The OLED display shows the latest temperature, humidity, timestamp and total number of records live, in large text.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

