こちらのプログラムを ESP32 に書き換えました。
M5Stack Core2: HTTP クライアント (Post)
Ubuntu 24.04 上の Arduino IDE 2.3.2 を使いました。
ボードは ESP32 Dev Module です。
ArduinoJSON を使います。
http_post.ino
// ---------------------------------------------------------------
/*
http_post.ino
Jul/25/2023
*/
// ---------------------------------------------------------------
#include <Arduino.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
WiFiMulti wifiMulti;
HTTPClient http;
const char *ssid = "rs500m-e1eaf5-1";
const char *password = "7f7a63e07b1c6";
int count = 0;
// ---------------------------------------------------------------
void setup()
{
Serial.begin(115200);
Serial.println("*** setup start ***");
wifiMulti.addAP(ssid, password);
Serial.print("\nConnecting Wifi...\n");
delay(3000);
Serial.println("*** setup *** aaa ***");
delay(1000);
Serial.println("*** setup ***");
}
// ---------------------------------------------------------------
void loop()
{
Serial.println("*** loop *** " + String(count));
delay(2000);
String url_target = "https://httpbin.org/post";
http_post_proc(url_target);
delay(3000);
count++;
}
// ---------------------------------------------------------------
void http_post_proc(String url_target)
{
DynamicJsonDocument doc(128);
char data_json[128];
doc["user"] = "jiro";
doc["password"] = "123456";
serializeJson(doc, data_json);
if((wifiMulti.run() == WL_CONNECTED)) {
Serial.print("[HTTP] begin...\n");
http.begin(url_target);
Serial.print("[HTTP] POST...\n");
int httpCode = http.POST((uint8_t*)data_json, strlen(data_json));
if(httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
}else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
else
{
Serial.print("connect failed");
}
}
// ---------------------------------------------------------------
ターミナルプログラム
cu -s 115200 -l /dev/ttyUSB0