Connecting to Wi-Fi with ESP32
Joining Wi-Fi
#include <WiFi.h>
#include "secrets.h" // defines WIFI_SSID, WIFI_PASS, API_TOKEN (not committed to Git)
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println(WiFi.localIP());
}
Keep credentials in a secrets.h file listed in .gitignore. For devices you give to others, use a provisioning method (such as a setup access point or Bluetooth) so users enter their own Wi-Fi details.
Sending readings to an API
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
void sendReading(float tempC, float humidity) {
WiFiClientSecure client;
client.setCACert(ROOT_CA_PEM); // verify the server's certificate
HTTPClient http;
http.begin(client, "https://api.example.com/v1/readings");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", String("Bearer ") + API_TOKEN);
String body = "{\"device\":\"greenhouse-1\",\"temp_c\":" + String(tempC, 1) +
",\"humidity\":" + String(humidity, 1) + "}";
int code = http.POST(body);
Serial.printf("POST -> %d\n", code);
http.end();
}
- Use HTTPS and verify certificates; avoid
setInsecure()outside quick experiments. - Give each device its own token with limited permissions so one stolen device does not compromise others.
- Handle failures: retry with backoff, and buffer readings if the network is down.
The receiving side
A small Flask endpoint (see API Design & REST) validates the token, checks the payload, stores readings and rate-limits each device.
Exercise
Send your weather station's readings every minute to a Flask API over HTTPS with a per-device token; store them in PostgreSQL and show the latest reading on a web page.
Check yourself
- Why keep Wi-Fi credentials out of the sketch file?
- Why give each device its own token?
- What should a device do when the network is down?
Your progress is saved in this browser only.
Submit for review (10 points)