Try Embedded

Pico W: upload sensor readings as JSON over HTTP

A Raspberry Pi Pico W joins Wi-Fi, POSTs a soil-moisture reading as JSON to a web API every 3 s, and takes its reporting interval from the server's answer.

Communication · Intermediate

In a real product: Soil moisture logger (Agriculture): A field sensor reports to the farm's cloud service, which tells it how often to report.

Most connected sensors do one thing over and over: read, send the reading to a web API, sleep. Here a Raspberry Pi Pico W reads a soil-moisture probe (a knob on GP26 stands in for it), sends it as JSON to api.farm.lab, and reads the server's answer, which says how many milliseconds to wait before the next reading. A red LED on GP15 lights when a reading could not be delivered.

What you'll learn

  • Joining WPA2 Wi-Fi with WiFi.begin() and checking the link before every request
  • HTTPClient: begin(), addHeader(), POST() with a JSON body, the status code and the answer's body
  • Taking settings from the server's answer, so the cloud can slow a whole fleet down without new firmware

How it works

WiFi.begin("TryEmbedded", "lab-pass-123") joins the access point; DHCP gives the board 192.168.4.2 and the DNS server 8.8.8.8. For each reading the sketch builds a small JSON object with snprintf, then HTTPClient looks the name up (DNS), opens a TCP connection to port 80, sends POST /readings with Content-Type: application/json, and returns the status code. 201 (Created) means the server stored it.

The answer's body is {"stored":true,"nextMs":3000}. The sketch finds "nextMs": with strstr and reads the number after it: no JSON library is needed for one field. If the request fails (a negative code: no connection, a timeout) the red LED lights, and the reading is tried again after the same interval.

The server is set in diagram.json under "network": the host api.farm.lab with a route for POST /readings. Its "responses" answer from the fourth upload on with nextMs 1000, as if the farm's operator wanted more data. Open the Network panel to see the join, every DNS lookup, connection and request, with the JSON the board sent.

Try this

  • Add "faults": { "outages": [{ "fromMs": 9000, "toMs": 12000 }] } to the network: the uploads in the outage fail and the red LED lights until the network is back.
  • Send the board's uptime too: add "uptimeMs":%lu and millis() to the JSON.
  • Make the route answer "status": 503 and handle it: wait longer before trying again.

sketch.ino

// Raspberry Pi Pico W (Arduino core): a soil-moisture logger. Joins Wi-Fi, POSTs the reading on GP26 as JSON to
// http://api.farm.lab/readings, and waits as long as the server's answer says ("nextMs"). A red LED on GP15 lights
// when an upload fails.
#include <WiFi.h>
#include <HTTPClient.h>

const int PROBE = 26;
const int FAILED = 15;
unsigned long intervalMs = 3000;

void setup() {
  Serial.begin(115200);
  pinMode(FAILED, OUTPUT);
  analogReadResolution(12);
  WiFi.setTimeout(3000);
  WiFi.begin("TryEmbedded", "lab-pass-123");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("joining TryEmbedded...");
    delay(500);
  }
  Serial.print("joined, address ");
  Serial.println(WiFi.localIP());
}

void upload() {
  int moisture = analogRead(PROBE) * 100 / 4095;   // percent
  char json[64];
  snprintf(json, sizeof json, "{\"device\":\"field-7\",\"moisture\":%d}", moisture);

  HTTPClient http;
  http.setTimeout(2000);
  http.begin("http://api.farm.lab/readings");
  http.addHeader("Content-Type", "application/json");
  int code = http.POST(json);
  Serial.printf("sent %s: %d\n", json, code);
  if (code == 201) {
    String answer = http.getString();
    const char *next = strstr(answer.c_str(), "\"nextMs\":");
    if (next) intervalMs = strtoul(next + 9, nullptr, 10);
  }
  digitalWrite(FAILED, code == 201 ? LOW : HIGH);
  http.end();
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) upload();
  else digitalWrite(FAILED, HIGH);
  delay(intervalMs);
}

Lessons behind it