http-get.ino

Arduino MKR WiFi 1010 · File : http-get.ino · Language : Arduino · Use case : Consulter une API HTTP depuis le WiFi

Fetching web data with the MKR WiFi 1010: join the access point, open a TCP socket on port 80, GET a free weather API, then drain the reply to the serial port. The template of every sober embedded HTTP client.

Hardware

An Arduino MKR WiFi 1010 (SAMD21 microcontroller, WINC1500 Wi-Fi module, no Bluetooth, USB or LiPo power on J6). MKR WiFi 1010 on an outbound-Internet network; no signup needed for the API used.

Wiring

No wiring; check the WiFi allows the outbound port (80) — some captive portals block it.

How it works

WiFiClient implements Print/Stream: the HTTP header is written by hand, then read until close or timeout. The raw JSON reply prints as is, ready to parse.

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

Move to WiFiSSLClient on port 443 for HTTPS (needs the root certificate in flash), or add a minimal JSON parser such as ArduinoJson.

http-get.ino

// Client HTTP sur le reseau local/WAN (MKR WiFi 1010, WiFi101).
#include <SPI.h>
#include <WiFi101.h>

const char SSID[] = "MonReseau";
const char PASS[] = "motdepassewifi";
const char HOTE[] = "api.open-meteo.com";
const char CHEMIN[] = "/v1/forecast?latitude=45.5&longitude=4.8&current=temperature_2m";

WiFiClient client;

void connexion() {
  WiFi.begin(WPA_PASS_PHRASE, SSID, PASS);
  unsigned long t = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t < 20000) delay(100);
}

void setup() {
  Serial.begin(9600);
  while (!Serial);
  connexion();
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println(F("WiFi indisponible"));
    while (true);
  }
  Serial.println(WiFi.localIP());
  if (client.connect(HOTE, 80)) {
    client.print(String("GET ") + CHEMIN + " HTTP/1.1\r\n" +
                 "Host: " + HOTE + "\r\nConnection: close\r\n\r\n");
    unsigned long t = millis();
    while (client.connected() && millis() - t < 10000)
      while (client.available()) Serial.write(client.read());
    client.stop();
  } else Serial.println(F("TCP KO"));
}

void loop() {}

← Back to the board