http-post.ino

Arduino MKR WiFi 1010 · File : http-post.ino · Language : Arduino · Use case : Publier une mesure vers une API REST en POST

Local telemetry from the MKR WiFi 1010: every minute an analog reading leaves as JSON POST to an API on your network (Flask, Node, InfluxDB...). The exact template time-series databases expect, testable with ten lines of Python server.

Hardware

An Arduino MKR WiFi 1010 (SAMD21 microcontroller, WINC1500 Wi-Fi module, no Bluetooth, USB or LiPo power on J6). MKR WiFi 1010 on the LAN, listening machine running an HTTP server that accepts POST (static IP advised).

Wiring

No wiring; pin the server IP with a static DHCP lease to avoid surprises.

How it works

The JSON body is built with String, Content-Length computed automatically. The server reply is read and discarded to release the socket cleanly before the next cycle.

Running it

Install Arduino SAMD Boards and the WiFi101 library, select the board, upload. Wi-Fi runs on 2.4 GHz only: check that your access point is not 5 GHz only.

Variants

Add an authentication header (Bearer), switch to HTTPS with WiFiSSLClient, or buffer readings in RAM for an economical batched POST.

http-post.ino

// POST JSON periodique MKR WiFi 1010 vers une API locale (Flask/Node).
#include <SPI.h>
#include <WiFi101.h>

const char SSID[] = "MonReseau";
const char PASS[] = "motdepassewifi";
const char SERVEUR[] = "192.168.1.50"; // machine d'ecoute
const int PORT = 5000;

WiFiClient client;
unsigned long dernier = 0;

void setup() {
  Serial.begin(9600);
  WiFi.begin(WPA_PASS_PHRASE, SSID, PASS);
  while (WiFi.status() != WL_CONNECTED) delay(100);
  Serial.println(WiFi.localIP());
}

void loop() {
  if (millis() - dernier < 60000) return; // 1/min
  dernier = millis();
  String json = "{\"capteur\":\"salon\",\"valeur\":" +
                String(analogRead(A1)) + "}";
  if (client.connect(SERVEUR, PORT)) {
    client.print(String("POST /mesures HTTP/1.1\r\nHost: ") + SERVEUR +
      "\r\nContent-Type: application/json\r\nContent-Length: " +
      json.length() + "\r\n\r\n" + json);
    delay(500);
    while (client.available()) client.read(); // vide la reponse
    client.stop();
    Serial.println("POST " + json);
  } else Serial.println(F("serveur KO"));
}

← Back to the board