http-post-capteur.ino

Arduino MKR GSM 1400 · File : http-post-capteur.ino · Language : Arduino · Use case : Publier une mesure de capteur vers une API par POST HTTP

Standalone GPRS telemetry: every minute the MKR GSM 1400 reads an analog input, builds a small JSON and POSTs it to an HTTP API. A complete field-station pattern with no WiFi or cable needed.

Hardware

An Arduino MKR GSM 1400 (SAMD21 microcontroller, 2G/GPRS cellular modem, external antenna, powered by a LiPo battery on the J6 connector or over USB). 2G data SIM, antenna, and an analog input (potentiometer or 0-3.3 V sensor on A1) for this example.

Wiring

Sensor to A1 and GND, 3.3 V for the sensor supply; never exceed 3.3 V on SAMD21 pins.

How it works

analogRead converts the voltage (3.3 V reference, 10 bits), the JSON is assembled with String, then POSTed with a computed Content-Length. The server reply is drained to release the socket.

Running it

In the Arduino IDE, install the Arduino SAMD Boards package, select the MKR GSM 1400 board, then upload. Network examples assume an active data SIM is inserted, the antenna is screwed on, and 2G coverage still exists in your area.

Variants

Add a BME280 on I2C for temperature/humidity, switch to HTTPS, or batch several readings per POST to save data credit.

http-post-capteur.ino

// Publication periodique d'une mesure via POST JSON sur GPRS.
#include <MKRGSM.h>

const char PIN_SIM[] = "0000";
const char APN[] = "sl2g";
const char HOTE[] = "api.example.com";

GSM gsm; GSMGPRS gprs; GSMClient client;
const int BROCHE_ENTREE = A1;
unsigned long dernierEnvoi = 0;

void setup() {
  Serial.begin(9600);
  if (gsm.begin(PIN_SIM) != GSM_READY) while (true);
  while (gsm.waitNetworkReady(30) != ON_NET);
  gprs.attachGPRS(APN, GPRS_AUTOMATIC_BEARER, 1);
}

void loop() {
  if (millis() - dernierEnvoi < 60000) return;
  dernierEnvoi = millis();
  int brut = analogRead(BROCHE_ENTREE);
  String json = "{\"tension\":" + String(brut * (3.3 / 1023.0), 3) +
                ",\"uptime\":" + String(millis() / 1000) + "}";
  if (client.connect(HOTE, 80)) {
    client.print(String("POST /mesures HTTP/1.1\r\nHost: ") + HOTE +
      "\r\nContent-Type: application/json\r\nContent-Length: " +
      json.length() + "\r\n\r\n" + json);
    delay(1500); // laisser arriver la reponse serveur
    client.stop();
  }
}

← Back to the board