ESP-IDF: ESP32 HTTP GET Request (Time API)

This tutorial is a getting started guide to HTTP GET requests with the ESP32 board using ESP-IDF framework. HTTP Requests are fundamental to interact with web services to retrieve data from external sources, integrate with web APIs to access third-party services, and much more. Learn how to make HTTP GET requests and how to decode JSON data from TimeAPI.io.

ESP-IDF ESP32 HTTP GET Request Time API

Using Arduino IDE? Follow this tutorial instead: ESP32 HTTP GET with Arduino IDE

Prerequisites

Before following this guide, you need to install the ESP-IDF extension on VS Code IDE (Microsoft Visual Studio Code). Follow the next guide to install it, if you haven’t already:

You will also need an ESP32 development board model of your choice.

What are HTTP Requests?

The most common way to exchange data with another computer (server) on the internet is using the HTTP protocol.

HTTP (Hypertext Transfer Protocol) works through a client-server model. In this model, the client communicates with a server using HTTP requests. An HTTP request is a message sent by the client to a server, typically to request a specific action or retrieve information. The server sends a response back to the client also through HTTP.

ESP32 HTTP GET Request Client HTTP Reponse Server
  • Client: initiates communication through a request.
  • Server: receives and processes the request and returns a response.

The ESP32 can either be a client or a server. When it is a client, it sends requests to servers. When it is a server, it handles the client’s requests.

You might also like reading: ESP32 Web Server (ESP-IDF)

In this tutorial, we’ll take a look at the ESP32 as an HTTP client. Here are some examples of what you can do using HTTP requests with the ESP:

  • Get data from the internet: for example, time, current weather, stock prices, traffic updates, etc…
  • Datalogging: send data to the cloud to save your data online;
  • Remote control of your ESP32: by interacting with IoT platforms like Adafruit IO, Node-RED, and others. You can interact with your board remotely by exchanging data via HTTP requests;
  • Interact with third-party services to send notifications: SMS, emails, notifications, and much more…

Technical Overview of HTTP Requests

Let’s take a quick look at the technical aspects of HTTP requests. If this is your first time dealing with HTTP requests in a technical manner and it seems confusing, that’s perfectly normal.

For more information about the technical aspects of HTTP requests, we recommend the following resources:

HTTP Requests

An HTTP request consists of several parts. The main elements are: request line, headers, and body.

Request Line

The request line specifies the HTTP method, the resource being requested (the URL), and the version of the HTTP protocol being used. Common HTTP methods include GET, POST, PUT, and DELETE. For example:

GET /path/to/resource HTTP/1.1

Headers

Headers provide information about the request. It can include the host to which the client is sending the request, the type of content being sent or accepted, the user‑agent (which identifies the client making the request), and more. For example:

Host: example.com
User-Agent: ESP32
Accept: application/json

Body

The body is an optional content, and it contains data or information that we want to send to the server. This is used in POST and PUT requests. For example:

POST /submit-form HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=johndoe&password=secretpassword

HTTP Request Methods

The choice of HTTP method in a request indicates the intended action to be performed on the server. Some commonly used methods include:

  • GET: retrieve data from the server.
  • POST: submit data to be processed to a specified resource.
  • PUT: update a resource on the server.
  • DELETE: remove a resource from the server.

In this tutorial, we’ll focus on using GET requests with the ESP32.

HTTP Status Codes

After receiving an HTTP request, the server responds with an HTTP status code indicating the outcome of the request. Status codes fall into categories such as 2xx (successful), 3xx (redirection), 4xx (client error), and 5xx (server error). Some of the most common:

  • 200 OK: the request was successful.
  • 404 Not Found: the requested resource could not be found.

The Time API

To show you how to handle HTTP GET requests with the ESP32, we’ll request the time from TimeAPI.io.

The TimeAPI.io provides a simple HTTP interface to retrieve the current date and time based on
a timezone, including daylight saving time. Here’s an example of how you can use the Time API. You can make a request to the following URL endpoint:

https://timeapi.io/api/Time/current/zone?timeZone=<YOUR_TIMEZONE>

Replace <YOUR_TIMEZONE> with the desired time zone. For example, to get the current time in UTC, you can use:

https://timeapi.io/api/Time/current/zone?timeZone=UTC

You can also specify a specific city or region within a time zone, such as:

https://timeapi.io/api/Time/current/zone?timeZone=Europe/Lisbon

You can find the list of supported time zones at the AvailableTimeZones API endpoint, or you can read the complete documentation. After making the request, it will send a JSON with a response containing the following information:

{
  "year": 2026,
  "month": 6,
  "day": 4,
  "hour": 8,
  "minute": 24,
  "seconds": 12,
  "milliSeconds": 7,
  "dateTime": "2026-06-04T08:24:12.0076021",
  "date": "06/04/2026",
  "time": "08:24",
  "timeZone": "Europe/Lisbon",
  "dayOfWeek": "Thursday",
  "dstActive": true
}

Creating an ESP-IDF Template App Project for the ESP32

The ESP-IDF extension provides an easy way to create a project from scratch with all the required files and configurations generated automatically.

To create a new ESP-IDF project on VS Code, follow these steps:

  1. Open the ESP-IDF Espressif extension
  2. Expand the “Advanced” menu
  3. Click the “New Project Wizard” option
  4. Choose the “Use ESP-IDF v5.4.1” to select the framework version
ESP-IDF ESP32 Create Open New Project Wizard Menu

A new window opens, you need to fill in these fields:

  • Project Name: type the desired project name;
  • Enter Project Directory: click the folder icon and select the target folder to save all your project files. You can use any directory. Note: do NOT use a Google Drive / One Drive / Dropbox folder, because it will write/create many files during the building process. If it’s in a cloud folder, this process might be extremely slow;
  • ESP-IDF Target: select the target device chip, I’m using an ESP32 with the esp32s3 chip;
  • ESP-IDF Board: for the esp32s3 chip, I also need to select the configuration: ESP32-S chip (via builtin USB-JTAG);
  • Serial Port: while having your ESP32 board connected to your computer, select the correct COM port number that refers to your ESP32;
  • Choose Template: click the blue button to create a new project using a template.
ESP-IDF ESP32 Create Open New Project Wizard Menu Select Directory Board Template

In the menu, select the “ESP-IDF Templates” sample project and press the “Create project using template sample project” button.

ESP-IDF ESP32 Create New Sample Project using IDF Template

Opening the ESP-IDF Project on VS Code

After a few seconds, a notification will appear in a new window in VS Code. You can click “Open Project” to open the newly created ESP-IDF sample project template.

ESP-IDF ESP32 Open New Project Sample

IMPORTANT: if you didn’t see the notification that allows you to automatically open the ESP-IDF project on VS Code, you can easily do it by following these instructions:

Go to File > Open Folder…

ESP-IDF ESP32 Open Project Folder VS Code File Menu

Browse on your computer for the esp-idf-project folder (your project folder name that you’ve previously defined) and “Select Folder“.

ESP-IDF ESP32 Open Project VS Code Select Folder

That’s it! Your new ESP-IDF project template has been successfully created and opened.

ESP-IDF generates many files, folders, and subfolders for your project. For this guide, I recommend keeping all the default files unchanged; we will only modify the main.c file.

The example code will be written in the main.c file. To open it, follow these instructions:

  1. Open the project explorer by clicking the first icon on the left sidebar.
  2. Select your project folder name, in my case it’s “ESP-IDF-PROJECT“.
  3. Expand the “main” folder.
  4. Click the “main.c” file.
  5. The default main.c template file loads in the code window.
ESP-IDF ESP32 Open Project in a VS Code Browse to Main C File

Code: ESP32 HTTP GET Requests using ESP-IDF

Copy the following code to the main.c file. The following code is a basic example of how you can make a simple HTTP GET request to the TimeAPI.io website to get the current date and time.

/* 
    Rui Santos & Sara Santos - Random Nerd Tutorials
    https://RandomNerdTutorials.com/esp-idf-esp32-http-get/
*/
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "nvs_flash.h"
#include "esp_http_client.h"
#include "esp_crt_bundle.h"

// REPLACE WITH YOUR SSID AND PASSWORD
#define WIFI_SSID   "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASS   "REPLACE_WITH_YOUR_PASSWORD"

// REPLACE WITH YOUR TIME ZONE - https://timeapi.io/api/TimeZone/AvailableTimeZones
#define TIME_ZONE   "Europe/Lisbon"

// TimeAPI.io endpoint with timezone query
#define API_URL     "https://timeapi.io/api/time/current/zone?timeZone=" TIME_ZONE

// Tag for logging
static const char *TAG = "http_get";

// Buffer for HTTP response
#define BUF_SIZE    512
static char response_buf[BUF_SIZE];
static int  response_len = 0;

// HTTP event handler to collect response data from the request
static esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
    if (evt->event_id == HTTP_EVENT_ON_DATA) {
        int copy = evt->data_len;
        if (response_len + copy >= BUF_SIZE) copy = BUF_SIZE - response_len - 1;
        memcpy(response_buf + response_len, evt->data, copy);
        response_len += copy;
        response_buf[response_len] = '\0';
    }
    return ESP_OK;
}

// Function that extracts a JSON field (no library needed)
// Finds "key":"value" or "key":value and copies the value 
static int get_json_value(const char *json, const char *key, char *out, int out_size)
{
    char search[64];
    snprintf(search, sizeof(search), "\"%s\":", key);
    const char *p = strstr(json, search);
    if (!p) return 0;
    p += strlen(search);
    while (*p == ' ') p++;
    int is_string = (*p == '"');
    if (is_string) p++;
    int i = 0;
    while (*p && i < out_size - 1) {
        if (is_string && *p == '"') break;
        if (!is_string && (*p == ',' || *p == '}')) break;
        out[i++] = *p++;
    }
    out[i] = '\0';
    return i;
}

// Function that makes an HTTP GET request to the API, parses the JSON response, and prints the date and time
static void get_and_print_time(void)
{
    // Reset response buffer
    response_len = 0;
    memset(response_buf, 0, BUF_SIZE);

    // Configure HTTP client
    esp_http_client_config_t config = {
        .url               = API_URL,
        .event_handler     = http_event_handler,
        .crt_bundle_attach = esp_crt_bundle_attach,
    };

    // Initialize HTTP client and perform the HTTP GET request
    esp_http_client_handle_t client = esp_http_client_init(&config);
    esp_err_t err = esp_http_client_perform(client);

    // Check if the request was successful (ESP_OK and status code 200) and print the results
    if (err == ESP_OK) {
        int status = esp_http_client_get_status_code(client);
        if (status == 200) {
            // Extract fields (values) from the JSON response
            char date[20], time[20], day_of_week[16], tz[40];
            get_json_value(response_buf, "date",      date,        sizeof(date));
            get_json_value(response_buf, "time",      time,        sizeof(time));
            get_json_value(response_buf, "dayOfWeek", day_of_week, sizeof(day_of_week));
            get_json_value(response_buf, "timeZone",  tz,          sizeof(tz));
            // Print the results
            ESP_LOGI(TAG, "------------------------------------");
            ESP_LOGI(TAG, "Timezone: %s", tz);
            ESP_LOGI(TAG, "Date    : %s (%s)", date, day_of_week);
            ESP_LOGI(TAG, "Time    : %s", time);
            ESP_LOGI(TAG, "------------------------------------");
        } else {
            ESP_LOGW(TAG, "HTTP status %d", status);
        }
    } else {
        ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(err));
    }
    // Cleanup HTTP client
    esp_http_client_cleanup(client);
}

// Event group to signal when connected to Wi-Fi
static EventGroupHandle_t s_wifi_event_group;
#define WIFI_CONNECTED_BIT BIT0

// Wi-Fi and IP event handler
static void wifi_event_handler(void *arg, esp_event_base_t base,
                               int32_t id, void *data)
{
    if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
        ESP_LOGI(TAG, "Wi-Fi STA started. Connecting to %s...", WIFI_SSID);
        esp_wifi_connect();
    } else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
        ESP_LOGW(TAG, "Wi-Fi disconnected. Retrying connection...");
        esp_wifi_connect();
    } else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t *e = (ip_event_got_ip_t *)data;
        ESP_LOGI(TAG, "Got IP Address: " IPSTR, IP2STR(&e->ip_info.ip));
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}

// Initializes Wi-Fi in station mode and waits for connection
static void wifi_init(void)
{
    // Create event group to signal when connected
    s_wifi_event_group = xEventGroupCreate();

    // Initialize TCP/IP stack and event loop
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    // Create default Wi-Fi STA interface
    esp_netif_create_default_wifi_sta();
    // Initialize Wi-Fi
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    // Register event handlers
    esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
                                        wifi_event_handler, NULL, NULL);
    esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
                                        wifi_event_handler, NULL, NULL);

    // Configure Wi-Fi STA
    wifi_config_t wifi_cfg = {
        .sta = {
            .ssid     = WIFI_SSID,
            .password = WIFI_PASS,
        },
    };
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg));
    ESP_ERROR_CHECK(esp_wifi_start());

    ESP_LOGI(TAG, "Connecting to Wi-Fi...");

    // Wait until connected
    xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT,
                        pdFALSE, pdTRUE, portMAX_DELAY);
}

// Task that periodically makes an HTTP GET request to the API and prints the time
static void http_get_task(void *arg)
{
    while (true) {
        get_and_print_time();
        // Wait for 60 seconds before the next request
        vTaskDelay(pdMS_TO_TICKS(60000)); 
    }
}

void app_main(void)
{
    // Initialize NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    
    // Initialize Wi-Fi
    wifi_init();

    // Start the HTTP GET time fetching task
    xTaskCreate(http_get_task, "http_get_task", 8192, NULL, 5, NULL);
}

View raw code

You can modify the following line with your own time zone. A list of available time zones can be
found on the AvailableTimeZones endpoint.

#define TIME_ZONE    "REPLACE_WITH_YOUR_TIME_ZONE"

Example for the Portugal time zone:

#define TIME_ZONE    "Europe/Lisbon"

How the Code Works

In this section, we’ll take a look at the code to see how it works.

Libraries

We start by including the required libraries:

  • string.h – the standard C library used for string manipulation;
  • FreeRTOS.h – provides the core FreeRTOS types and functions;
  • task.h – allows to use task management;
  • esp_log.h – offers a framework to format log messages in the serial monitor for debugging;
  • esp_wifi.h – library for Wi-Fi configuration (station and access point modes and connection options);
  • esp_event.h – handles events like Wi-Fi status changes;
  • nvs_flash.h – stores key-value data in non-volatile storage (NVS) memory persistently ;
  • esp_http_client.h – provides a simple HTTP/HTTPS client for the ESP32. so you can perform GET and POST requests and handle their responses;
  • esp_crt_bundle.h – built-in trusted root CA certificate, so you can easily make an HTTPS request.
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "nvs_flash.h"
#include "esp_http_client.h"
#include "esp_crt_bundle.h"

Wi-Fi Configuration

Add your SSID and password, so that the ESP32 can establish an internet connection with your router.

#define WIFI_SSID   "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASS   "REPLACE_WITH_YOUR_PASSWORD"

TimeAPI Endpoint

You can modify the following example with your own time zone. A list of available time zones can be
found at the AvailableTimeZones endpoint.

#define TIME_ZONE    "REPLACE_WITH_YOUR_TIME_ZONE"

Example for the Portugal time zone:

#define TIME_ZONE    "Europe/Lisbon"

Next, define the API_URL:

#define API_URL     "https://timeapi.io/api/time/current/zone?timeZone=" TIME_ZONE

Logging Tag

The “http_get” prefix will be used to log all the debugging messages.

static const char *TAG = "http_get";

Buffer

Global buffer variables that will store the HTTP response body from the request.

#define BUF_SIZE    512
static char response_buf[BUF_SIZE];
static int  response_len = 0;

http_event_handler

When the ESP32 makes an HTTP request, the response body arrives in chunks rather than all at once. The http_event_handler() function appends the received data. The response_buf holds the entire JSON response body, ready for the values to be extracted.

static esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
    if (evt->event_id == HTTP_EVENT_ON_DATA) {
        int copy = evt->data_len;
        if (response_len + copy >= BUF_SIZE) copy = BUF_SIZE - response_len - 1;
        memcpy(response_buf + response_len, evt->data, copy);
        response_len += copy;
        response_buf[response_len] = '\0';
    }
    return ESP_OK;
}

get_json_value()

The get_json_value() function extracts the value of a specific key from a raw JSON string without using any additional libraries. Basically, it searches for the “key”: pattern and returns the value found.

static int get_json_value(const char *json, const char *key, char *out, int out_size)
{
    char search[64];
    snprintf(search, sizeof(search), "\"%s\":", key);
    const char *p = strstr(json, search);
    if (!p) return 0;
    p += strlen(search);
    while (*p == ' ') p++;
    int is_string = (*p == '"');
    if (is_string) p++;
    int i = 0;
    while (*p && i < out_size - 1) {
        if (is_string && *p == '"') break;
        if (!is_string && (*p == ',' || *p == '}')) break;
        out[i++] = *p++;
    }
    out[i] = '\0';
    return i;
}

Here’s the sample raw JSON:

{
  "year": 2026,
  "month": 6,
  "day": 4,
  "hour": 8,
  "minute": 24,
  "seconds": 12,
  "milliSeconds": 7,
  "dateTime": "2026-06-04T08:24:12.0076021",
  "date": "06/04/2026",
  "time": "08:24",
  "timeZone": "Europe/Lisbon",
  "dayOfWeek": "Thursday",
  "dstActive": true
}

If you call the function as shown in the next line, it searches for the key “date”: and returns the correct value 06/04/2026.

get_json_value(response_buf, "date", date, sizeof(date));

get_and_print_time()

Now, we’re going to prepare the request and learn how to handle the response.

Clear the global buffer before each new request:

response_len = 0;
memset(response_buf, 0, BUF_SIZE);

These next lines configure and initialize the HTTP client with the API_URL, and assign the http_event_handler callback that is triggered when new HTTP response data is received.

esp_http_client_config_t config = {
    .url               = API_URL,
    .event_handler     = http_event_handler,
    .crt_bundle_attach = esp_crt_bundle_attach,
};

esp_http_client_handle_t client = esp_http_client_init(&config);
esp_err_t err = esp_http_client_perform(client);

If the HTTP GET request is successful and returns a 200 status code, it calls get_json_value multiple times to extract the desired values (date, time, dayOfWeek, and timezone) from the raw JSON response, then prints them to the terminal.

if (err == ESP_OK) {
    int status = esp_http_client_get_status_code(client);
    if (status == 200) {
        // Extract fields (values) from the JSON response
        char date[20], time[20], day_of_week[16], tz[40];
        get_json_value(response_buf, "date",      date,        sizeof(date));
        get_json_value(response_buf, "time",      time,        sizeof(time));
        get_json_value(response_buf, "dayOfWeek", day_of_week, sizeof(day_of_week));
        get_json_value(response_buf, "timeZone",  tz,          sizeof(tz));
        // Print the results
        ESP_LOGI(TAG, "------------------------------------");
        ESP_LOGI(TAG, "Timezone: %s", tz);
        ESP_LOGI(TAG, "Date    : %s (%s)", date, day_of_week);
        ESP_LOGI(TAG, "Time    : %s", time);
        ESP_LOGI(TAG, "------------------------------------");
    } else {
        ESP_LOGW(TAG, "HTTP status %d", status);
    }
} else {
    ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(err));
}

Call the cleanup function at the end of the request to free up memory and resources that were used by the HTTP client.

esp_http_client_cleanup(client);

Wi-Fi and IP event handler

This callback function runs when an event related to Wi-Fi happens.

static void wifi_event_handler(void *arg, esp_event_base_t base,
                               int32_t id, void *data)
{
    if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
        ESP_LOGI(TAG, "Wi-Fi STA started. Connecting to %s...", WIFI_SSID);
        esp_wifi_connect();
    } else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
        ESP_LOGW(TAG, "Wi-Fi disconnected. Retrying connection...");
        esp_wifi_connect();
    } else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t *e = (ip_event_got_ip_t *)data;
        ESP_LOGI(TAG, "Got IP Address: " IPSTR, IP2STR(&e->ip_info.ip));
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}

For example, when the ESP32 gets assigned an IP address, it triggers the IP_EVENT that prints this message in the Serial Monitor:

ESP_LOGI(TAG, "Got IP Address: " IPSTR, IP2STR(&e->ip_info.ip));

wifi_init()

Create an event group to signal when connected:

s_wifi_event_group = xEventGroupCreate();

Then, initialize the TCP/IP stack required for network functions usage.

ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());

Start the Wi-Fi interface in station mode, so the ESP32 can connect to the router. It also initializes the Wi-Fi functionalities.

esp_netif_create_default_wifi_sta();

wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));

Assign the Wi-Fi events so that when the ESP32 establishes a Wi-Fi connection or gets an IP address, it runs the corresponding Wi-Fi event.

esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
                                    wifi_event_handler, NULL, NULL);
esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
                                    wifi_event_handler, NULL, NULL)

These next few lines set the SSID and password so the ESP32 can connect to your network, set the ESP in station mode, and start Wi-Fi.

wifi_config_t wifi_config = {
    .sta = {
        .ssid = WIFI_SSID,
        .password = WIFI_PASS,
    },
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());

Finally, wait until you have a Wi-Fi connection:

xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT,
                    pdFALSE, pdTRUE, portMAX_DELAY);

http_get_task()

The http_get_task() function is associated with the task that makes a new request to the API every 60 seconds and prints the date and time to the Terminal window.

static void http_get_task(void *arg)
{
    while (true) {
        get_and_print_time();
        // Wait for 60 seconds before the next request
        vTaskDelay(pdMS_TO_TICKS(60000)); 
    }
}

app_main(void)

When creating an ESP-IDF project, the app_main function will always be called to run. This function is where you need to write your code for any ESP-IDF applications; it is the equivalent of the setup() in Arduino programming. When the ESP32 boots, the ESP-IDF framework calls app_main.

void app_main(void)
{
    // your code goes here
}

In the app_main(void) function, you start by initializing the NVS (storage). The ESP32 stores the Wi-Fi settings in flash.

esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
    ESP_ERROR_CHECK(nvs_flash_erase());
    ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);

Initialize the Wi-Fi connection with your router:

wifi_init();

Finally, start the HTTP GET time task that keeps fetching the new date and time from the API.

xTaskCreate(http_get_task, "http_get_task", 8192, NULL, 5, NULL);

Build and Flash Code to the ESP32 Board

To build and flash ESP-IDF code to the ESP32, you always need to follow this procedure. You need to select the flash method (UART), the COM port number, the target device (ESP32), build the code, and finally, flash it to the board. All these commands are available in the bottom menu bar of VS Code.

Make sure all your options are correct (they may already be properly configured if you used the project wizard).

VS Code ESP-IDF Check All the Configured Settings UART COM Port Target Board

However, if your setup is not correct, follow the next instructions to ensure everything is set up correctly. First, click the “Star” icon and select the flash method as UART.

VS Code ESP-IDF Select Flash UART Option to Program Flash ESP32

While the ESP32 board is connected to your computer, click the COM Port (plug icon) and select the correct port number that refers to your ESP32.

VS Code ESP-IDF Programming ESP32 Board Select Correct COM Port Number

You also need to select the target device. Click on the chip icon at the bottom bar. In my case, I have an ESP32 with the esp32s3 chip.

VS Code Select the ESP32 S3 or Correct Target Device ESP-IDF

For this board, I also need to select the configuration: ESP32-S chip (via builtin USB-JTAG).

VS Code ESP-IDF Select the ESP32 S3 chip via built in USB JTAG Target Device

Finally, your command bar at the bottom of VS Code should have similar options selected.

VS Code ESP-IDF Check All the Configured Settings UART COM Port Target Board

Now, you can build the project by clicking the wrench icon (Build Project) as shown in the image below.

VS Code Build Project Example Code ESP32 ESP-IDF

The first time you build a project, it usually takes a bit more time. Once completed, it should print a similar message in the Terminal menu and show a “Build Successfully” message.

VS Code Build Example Project ESP32 ESP-IDF Success Message

This is the final step. You can now flash the ESP-IDF project to the ESP32 by clicking the “Flash Device” button (thunder icon).

VS Code Flash Hello World Code Project to ESP32 ESP-IDF

Depending on your board, you might need to hold down the on-board BOOT button on your ESP32 to put it into flashing mode. Once the process is completed, it will pop up an info message saying “Flash Done“.

VS Code Flash Hello World Project to ESP32 ESP-IDF Done Success Message

Demonstration

If you followed all the steps, the example should be running successfully on your board. Open your Terminal window and click the “Monitor Device” tool that is illustrated with a screen icon.

VS Code Open Terminal Window Monitor Device ESP32 ESP-IDF

The ESP32 connects to Wi-Fi and prints its IP address. Then, it makes an HTTP GET request every 60 seconds to TimeAPI.io and prints the date and time on the Terminal window according to your time zone.

ESP-IDF ESP32 HTTP GET Request TimeAPI Date Time Demonstration

Here’s an overview of how the HTTP GET request works:

ESP-IDF ESP32 HTTP GET Request TimeAPI Demonstration

Wrapping Up

In this tutorial, you learned how to program the ESP32 with the ESP-IDF framework using VS Code to make HTTP GET requests to an online API that gives you the current date and time.

You might find it helpful to read other ESP-IDF guides:

Meanwhile, you can check our ESP32 resources (with Arduino IDE) to learn more about the ESP32 board:

Thanks for reading.



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 »

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.