ESP32: Temperature on TM1637 7-Segment Display (WeatherAPI)

In this project, we’ll display the current temperature for your city (or any city of your choice) on the TM1637 7-segment display. To get the temperature, we’ll make HTTP requests with the ESP32 to the WeatherAPI (no sensor needed).

ESP32: Display Temperature on TM1637 7-Segment Display (WeatherAPI)

This is a great project to put into practice how to make HTTP requests with the ESP32 and use the TM1637 7-segment display. For in-depth tutorials about these subjects, check the following articles:

Prerequisites

Before proceeding, make sure you have the Arduino IDE installed and the ESP32 boards. Follow the next tutorial if you haven’t already:

Project Overview

In this project, we’ll display the current temperature for your city on the TM1637 4-Digit 7-Segment display. We’ll get the temperature from the Weather API.

Here’s a quick overview of the steps we need to follow to create this project:

  1. Initialize the display and set its brightness;
  2. Initialize Wi-Fi and connect the ESP32 to your local network so that it can get data from the internet.
  3. Make a request to the WeatherAPI to get temperature for your choosen location.
  4. Show the temperature in the display (alternate between temperature in Celsius and in Fahrenheit degrees).
  5. Every hour, make a new request to the WeatherAPI to get more recent data.

TM1637 4-Digit LED 7-Segment Display

The TM1637 4-Digit LED 7-Segment display is a display module that combines four 7-segment digits in a single display that can be controlled via the TM1637 driver. The particular module we’re using here has four digits separated by a colon between the second and third digits. This layout is ideal for creating a digital clock, with the hour on one side of the colon and the minutes on the other.

TM1637 4-Digit 7-Segment Display

Weather API

In this project, we’ll display the current temperature for your city on the display. We’ll get the temperature from the Weather API.

This API is free and provides useful information about the weather in almost any location in the world.

Weather forecaster example

We’ll get the temperature for your location and display it on the 7-segment display module.

Getting Your API Key

  1. Go to the Weather API website: weatherapi.com/
  2. Signup to create an account.
  3. After verifying your account, login into your account.
  4. On your dashboard at weatherapi.com/my/ , you’ll find your API key (even though it says the trial will end, you can continue using your API key freely).
Weather API Key

Copy the API key to a safe place because you’ll need it later.

To pull information on the weather in your chosen location, enter the following URL in your web browser, but insert your location and API key in the right places:

https://api.weatherapi.com/v1/current.json?q=YOUR_LOCATION+&key=YOUR_API_KEY'

For example, in my case:

https://api.weatherapi.com/v1/current.json?q=Oporto+&key=d1578a064b07453c917164350240106'

Copy your URL and paste it into your browser, and the API will return information corresponding to your local weather. For example:

{
"location": {
"name": "Oporto",
"region": "Porto",
"country": "Portugal",
"lat": 41.15,
"lon": -8.62,
"tz_id": "Europe/Lisbon",
"localtime_epoch": 1719843562,
"localtime": "2024-07-01 15:19"
},
"current": {
"last_updated_epoch": 1719843300,
"last_updated": "2024-07-01 15:15",
"temp_c": 22.3,
"temp_f": 72.1,
"is_day": 1,
"condition": {
"text": "Sunny",
"icon": "//cdn.weatherapi.com/weather/64x64/day/113.png",
"code": 1000
},
"wind_mph": 10.5,
"wind_kph": 16.9,
"wind_degree": 310,
"wind_dir": "NW",
"pressure_mb": 1021,
"pressure_in": 30.15,
"precip_mm": 0,
"precip_in": 0,
"humidity": 69,
"cloud": 0,
"feelslike_c": 24.7,
"feelslike_f": 76.4,
"windchill_c": 21.9,
"windchill_f": 71.5,
"heatindex_c": 24.6,
"heatindex_f": 76.2,
"dewpoint_c": 15,
"dewpoint_f": 58.9,
"vis_km": 10,
"vis_miles": 6,
"uv": 6,
"gust_mph": 15.4,
"gust_kph": 24.7
}
}

From this JSON, we can easily get the temperature for your location, either in Celsius or Fahrenheit: temp_c and temp_f.

Parts Required

For this project, you need the following parts:

TM1637 Display Parts Required Digital Clock

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Wiring the TM1637 4-Digit 7-Segment Display to the ESP32

TM1637 Display Module Pins CLK DIO VCC GND

Wiring the display to the ESP32 is quite simple, as it only requires two digital pins: CLK and DI/O.

TM1637 DisplayESP32
CLKAny digital pin (for example: GPIO 19)*
DIOAny digital pin (for example: GPIO 18)*
VCCVIN
GNDGND

* you can use any other suitable GPIOs. Check the ESP32 Pinout Guide:

We’ll connect the CLK pin to GPIO 19, and the DIO pin to GPIO 18, but you can use a different combination of pins.

TM1637 Display - Wiring to the ESP32

Installing Libraries

For this project, you need to instal the TM1637 library by avishorp to interface with the TM1637 display, and the ArduinoJSON library from bblanchon to handle the JSON data that is returned by the API.

Installing the TM1637 Library

There are several libraries to interface the TM1637 display with the ESP32. We’ll use the TM1637.h library by avishorp (even though it hasn’t been updated for several years, it still works well, and it’s very easy to use).

You can install the library via the Arduino IDE Library Manager. Search for TM1637 and install the library by avishorp.

Install TM1637 Library in Arduino IDE

Installing Libraries

For this example, you also need to install the ArduinoJSON library by bblanchon. You can install it in the Arduino Library Manager.

Install ArduinoJSON library Arduino IDE

Code – ESP32 with TM1637: Temperature Display

You can upload the following code to your board. You need to:

  • Insert your SSID and password;
  • Insert your WeatherAPI API key;
  • Insert the city where you want to get the temperature for.
/*
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at https://RandomNerdTutorials.com/esp32-tm1637-4-digit-7-segment-display-arduino/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <TM1637Display.h>

// Wi-Fi credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

const char* api_key = "REPLACE_WITH_YOUR_WeatherAPI_API_Key";
const char* location = "Oporto";  // "q" Parameter documentation for location: https://www.weatherapi.com/docs/#intro-request

// Request URL
String url = "https://api.weatherapi.com/v1/current.json?q=" + String(location) + "&key=" + String(api_key);

// TM1637 pins
#define CLK 19
#define DIO 18

TM1637Display display(CLK, DIO);

// Create the °C Symbol
const uint8_t Celsius[] = {
  SEG_A | SEG_B | SEG_F | SEG_G,  // Circle
  SEG_A | SEG_D | SEG_E | SEG_F   // C
};

// Create the °F Symbol
const uint8_t Fahrenheit[] = {
  SEG_A | SEG_B | SEG_F | SEG_G,  // Circle
  SEG_F | SEG_E | SEG_A | SEG_G   // F
};

// Global variables for temperatures and timers
float currentTempC = 9999;  // Initial error value
float currentTempF = 9999;  // Initial error value
unsigned long lastFetchTime = 0;
const unsigned long fetchInterval = 3600000UL;  // 1 hour in milliseconds

// Init Wifi
void initWiFi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connection successful");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

bool updateTemperatures() {
  HTTPClient http;
  http.begin(url);

  int httpCode = http.GET();

  if (httpCode == HTTP_CODE_OK) {  // Check for 200 specifically
    String payload = http.getString();
    Serial.print(payload);

    // Parse JSON
    StaticJsonDocument<1024> doc; // Adjust size if needed based on response
    DeserializationError error = deserializeJson(doc, payload);

    if (error) {
      Serial.print("JSON parsing failed: ");
      Serial.println(error.c_str());
      http.end();
      return false;
    }

    // Get both temperatures
    currentTempC = doc["current"]["temp_c"];
    currentTempF = doc["current"]["temp_f"];
    http.end();
    return true;
  } else {
    Serial.print("Error during request: ");
    Serial.println(httpCode);
    http.end();
    return false;
  }
}

void setup() {
  Serial.begin(115200);
  delay(1000); // Give time for Serial to initialize

  // Connect to Wi-Fi
  initWiFi();

  display.setBrightness(7);  // Set the display brightness (0-7)

  // Initial fetch
  if (updateTemperatures()) {
    lastFetchTime = millis();
  }
}

void loop() {
  // Check if it's time to fetch new data
  if (millis() - lastFetchTime >= fetchInterval) {
    if (updateTemperatures()) {
      lastFetchTime = millis();
    } else {
      // If failed, try again next loop 
      Serial.println("Fetch failed, keeping old values.");
    }
  }

  // Show Celsius
  Serial.print("Temperature in Celsius: ");
  Serial.println(currentTempC, 2);
  
  int roundedTempC = round(currentTempC);
  display.showNumberDec(roundedTempC, false, 2, 0);
  display.setSegments(Celsius, 2, 2);

  delay(5000);

  // Show Fahrenheit
  Serial.print("Temperature in Fahrenheit: ");
  Serial.println(currentTempF, 2);

  int roundedTempF = round(currentTempF);
  display.showNumberDec(roundedTempF, false, 2, 0);
  display.setSegments(Fahrenheit, 2, 2);

  delay(5000);
}

View raw code

How Does the Code Work?

Let’s take a quick look at the relevant parts of the code for this tutorial.

Including Libraries

We start by including the required libraries.

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <TM1637Display.h>

Network Credentials

Insert your network credentials in the following lines.

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Weather API

Insert your WeatherAPI key and the location you want to get data for.

const char* api_key = "REPLACE_WITH_YOUR_API_KEY";
const char* location = "REPLACE_WITH_YOUR_LOCATION";

This is the request URL that will return the weather data.

String url = "https://api.weatherapi.com/v1/current.json?q=" + String(location) + "&key=" + String(api_key);

TM1637 Display

Set the pins that are controlling the display and initialize an instance of the display called display.

// TM1637 pins
#define CLK 19
#define DIO 18

TM1637Display display(CLK, DIO);

Create an array with the required segments to create the ºC and ºF symbols.

// Create the °C Symbol
const uint8_t Celsius[] = {
  SEG_A | SEG_B | SEG_F | SEG_G,  // Circle
  SEG_A | SEG_D | SEG_E | SEG_F   // C
};

// Create the °F Symbol
const uint8_t Fahrenheit[] = {
  SEG_A | SEG_B | SEG_F | SEG_G,  // Circle
  SEG_F | SEG_E | SEG_A | SEG_G   // F
};

The SEG_A, SEG_B, and so on are references to their specific bytes (these are defined in the library .h file). To learn more about how to turn on/off specific segments, check this tutorial about the TM1637.

Global variables

Create global variables to store the temperature in Celsius and Fahrenheit.

float currentTempC = 9999;  // Initial error value
float currentTempF = 9999;  // Initial error value

And auxiliar variables to count the time to make a request to the API every hour.

unsigned long lastFetchTime = 0;
const unsigned long fetchInterval = 3600000UL;  // 1 hour in milliseconds

Initialize Wi-Fi

The initWiFi() function will initialize Wi-Fi and connect to your network using the inserted credentials.

// Init Wifi
void initWiFi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connection successful");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

Get/Update the Temperatures

The updateTemperatures() function makes a request to the WeatherAPI request URL.

The request returns a bunch of weather data as we’ve seen previously. We print all data to the Serial Monitor.

bool updateTemperatures() {
HTTPClient http;
http.begin(url);

int httpCode = http.GET();

if (httpCode == HTTP_CODE_OK) {  // Check for 200 specifically
  String payload = http.getString();
  Serial.print(payload);

Then, we only save the data we’re interested in. In this case, the temperature in Celsius and Fahrenheit. We save them in the currentTempC and currentTempF variables.

currentTempC = doc["current"]["temp_c"];
currentTempF = doc["current"]["temp_f"];

If everything goes well with the request, the function returns true. Otherwise, it returns false.

setup()

In the setup(), we initialize the Serial Monitor, connect to Wi-Fi, and set the display brightness.

void setup() {
  Serial.begin(115200);
  delay(1000); // Give time for Serial to initialize

  // Connect to Wi-Fi
  initWiFi();

  display.setBrightness(7);  // Set the display brightness (0-7)

Then, we make our first request to the API to get the current temperatures when the code first runs. From that time on, we also start counting the time to check later in the loop() if it’s time to make another request.

// Initial fetch
if (updateTemperatures()) {
  lastFetchTime = millis();
}

loop()

In the loop(), we’re constantly checking when it’s time to get new values.

// Check if it's time to fetch new data
if (millis() - lastFetchTime >= fetchInterval) {
  if (updateTemperatures()) {
    lastFetchTime = millis();
  } else {
    // If failed, try again next loop 
    Serial.println("Fetch failed, keeping old values.");
  }
}

Then, in the display, we’re alternating between showing the temperature in Celsius and in Fahrenheit every five seconds.

// Show Celsius
Serial.print("Temperature in Celsius: ");
Serial.println(currentTempC, 2);
  
int roundedTempC = round(currentTempC);
display.showNumberDec(roundedTempC, false, 2, 0);
display.setSegments(Celsius, 2, 2);

delay(5000);

// Show Fahrenheit
Serial.print("Temperature in Fahrenheit: ");
Serial.println(currentTempF, 2);

int roundedTempF = round(currentTempF);
display.showNumberDec(roundedTempF, false, 2, 0);
display.setSegments(Fahrenheit, 2, 2);

delay(5000);

Since the temperature values come as float variables, we need to convert them to integers. To do that, we use the round() function to round the number. For example:

int roundedTempC = round(currentTempC);

We call the showNumberDec() function to display the values.

display.showNumberDec(roundedTempC, false, 2, 0);

Finally, call the setSegments() function to display the ºC and ºF Units.

display.setSegments(Celsius, 2, 2);

Demonstration

Upload the code to your ESP32 board. Don’t forget to insert your SSID and password in the code, as well as the API key, and your location.

You should get a successful message on the Serial Monitor.

Get Temperature from API - ESP32 - Serial Monitor

And the temperature in Celsius and Fahrenheit degrees will show up alternating on the display.

Wrapping Up

In this tutorial, you learned how to create a temperature display with the ESP32 and the TM1637 display. We got the data about temperature from the WeatherAPI. That API provides lots of information about the weather in your choosen location. You can easily adjust this project to display more data from the API.

We have similar tutorials that you may also like:

Finally, if you’d like to learn and build more with the ESP32, check out our resources:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.