HTTP

Mengirim Data dari ESP32 dengan HTTP POST

Berikut ini contoh mengirim data dari ESP32 ke web server sederhana. Protokol yang dipakai adalah HTTP POST

Kode di ESP32:

// urlencoded
// https://randomnerdtutorials.com/esp32-http-get-post-arduino/#http-post
// https://docs.arduino.cc/libraries/httpclient/
// receiving JSON POST https://www.geeksforgeeks.org/how-to-receive-json-post-with-php/

#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <WiFiMulti.h>

const char *AP_SSID = "AP Name";
const char *AP_PWD = "AP password";

void setup() {
  Serial.begin(115200);

  WiFi.begin(AP_SSID, AP_PWD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  Serial.print("ESP32 Web Server's IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  postDataToServer();
  delay(10000);  // delay 10 seconds
}
int counter = 0;
void postDataToServer() {
  Serial.println("Posting POST data to server...");
  // Block until we are able to connect to the WiFi access point
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("http://192.168.0.139/post.php");
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    // parameter POST dummy, kecuali counter yang diupdate teratur

    String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&value1=24.25&value2=49.54&value3=1005.14&counter=" + String(counter);
    int httpResponseCode = http.POST(httpRequestData);
    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.println(httpResponseCode);
      Serial.println(response);  // cek untuk debugging

    } else {
      Serial.print("error code");
      Serial.print(httpResponseCode);
      // error codes from https://github.com/amcewen/HttpClient/blob/master/HttpClient.h
      // static const int HTTP_ERROR_CONNECTION_FAILED =-1;
      // static const int HTTP_ERROR_API =-2;
      // static const int HTTP_ERROR_TIMED_OUT =-3;
      // static const int HTTP_ERROR_INVALID_RESPONSE =-4;
    }
  }
  counter++;
}

Berikut ini kode PHP di web server