Try Embedded

Weather over Wi-Fi (ESP32-C3)

Join the Wi-Fi, set the clock over NTP, fetch the temperature from a web API every 10 s and post each reading back.

Communication · Intermediate

In a real product: Weather display (Smart home): Fetches the forecast from a web API and shows it at home.

An ESP32 is usually on a network: it fetches settings and data from a server and reports what it measures. Here the ESP32-C3 joins the simulated access point, asks a web API for the temperature every 10 seconds, lights the LED when it is above 25 °C, and posts the reading back. The time in front of each line comes from NTP.

What you'll learn

  • Joining a Wi-Fi network and waiting for an address
  • An HTTP GET and POST with HTTPClient, and checking the status code
  • Setting the clock with configTime and reading it with getLocalTime

How it works

WiFi.begin starts joining in the background; the sketch waits until WiFi.status() is WL_CONNECTED. The access point gives the board 192.168.4.2. When it asks for api.weather.lab, DNS answers with the host's address, and the sketch opens a TCP connection to it and sends GET /now?city=pune. The answer is a JSON body; tempFrom finds the number after "temp":.

The network is simulated and nothing goes to the internet. The network section of diagram.json lists the hosts and what each of their routes answers, and the date and time NTP gives at the start of the run. Change the body of /now and run again to see the LED go out.

configTime asks pool.ntp.org for the time in the background, so the first reading has no time in front of it: getLocalTime(&t, 0) does not wait. The posted: 201 lines are the API's answer to each POST.

Try this

  • Set "temp" in the /now route to 21.0 and run: the LED stays off.
  • Give the /now route "status": 503 and handle the failure: retry after 1 s, three times, before waiting again.
  • Change SSID to another name: the sketch never joins. Add a timeout that prints why.

sketch.ino

// Joins the Wi-Fi, sets the clock over NTP, then every 10 s fetches the temperature from a web API, lights the LED
// on GPIO 4 when it is above 25 C, and posts the reading back.
#include <WiFi.h>
#include <HTTPClient.h>
#include <time.h>

const char *SSID = "TryEmbedded";
const char *PASSWORD = "";
const char *API = "http://api.weather.lab";
const int LED = 4;

void connectWifi() {
  Serial.print("Joining ");
  Serial.print(SSID);
  WiFi.begin(SSID, PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print('.');
  }
  Serial.print(" got ");
  Serial.println(WiFi.localIP());
}

// The number after "temp": in a JSON body, or NAN when it is not there.
float tempFrom(const String &json) {
  int at = json.indexOf("\"temp\":");
  return at < 0 ? NAN : json.substring(at + 7).toFloat();
}

void printTime() {
  struct tm t;
  if (getLocalTime(&t, 0)) Serial.printf("%02d:%02d:%02d ", t.tm_hour, t.tm_min, t.tm_sec);
}

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  connectWifi();
  configTime(0, 0, "pool.ntp.org");   // UTC; the time arrives a moment later
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) connectWifi();

  HTTPClient http;
  http.begin(String(API) + "/now?city=pune");
  int code = http.GET();
  printTime();
  if (code == 200) {
    float temp = tempFrom(http.getString());
    Serial.printf("temperature %.1f C\n", temp);
    digitalWrite(LED, temp > 25 ? HIGH : LOW);
    http.end();

    http.begin(String(API) + "/readings");
    http.addHeader("Content-Type", "application/json");
    int stored = http.POST(String("{\"temp\":") + temp + "}");
    Serial.printf("posted: %d\n", stored);
  } else {
    Serial.printf("GET failed: %d %s\n", code, http.errorToString(code).c_str());
  }
  http.end();
  delay(10000);
}

Lessons behind it