0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

M5Stack Core2: HTTP クライアント (Post)

Last updated at Posted at 2021-08-31
http_post/http_post.ino
// ---------------------------------------------------------------
/*
	http_post.ino

						Jul/08/2023
*/
// ---------------------------------------------------------------
#include <M5Core2.h>
#include <Arduino.h>

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

WiFiMulti wifiMulti;
HTTPClient http;

const char *ssid = "some-ssid";
const char *password = "some-password";

int count = 0;

// ---------------------------------------------------------------
void setup()
{
	M5.begin();
	M5.Lcd.setBrightness(32);

	wifiMulti.addAP(ssid, password);
	M5.Lcd.print("\nConnecting Wifi...\n");

	delay(3000);
	Serial.println("*** setup *** aaa ***");
	delay(1000);

	String url_target = "https://httpbin.org/post";

	http_post_proc(url_target);
	delay(5000);

	Serial.println("*** setup ***");
}

// ---------------------------------------------------------------
void loop()
{
	Serial.println("*** loop *** " + String(count));
	M5.Lcd.setTextSize(3);
	M5.Lcd.setCursor(5,30);
	M5.Lcd.println("*** loop *** " + String(count));
  String url_target = "https://httpbin.org/post";

	http_post_proc(url_target);

	delay(3000);
	M5.Lcd.clear();
	delay(1000);
	M5.Lcd.fillScreen(WHITE);
	delay(1000);
	count++;
}

// ---------------------------------------------------------------
void http_post_proc(String url_target)
{
  	M5.Lcd.setTextSize(1);
	DynamicJsonDocument doc(128);
	char data_json[128];

	doc["user"] = "jiro";
	doc["password"] = "123456";
	serializeJson(doc, data_json);

	if((wifiMulti.run() == WL_CONNECTED)) {
		M5.Lcd.print("[HTTP] begin...\n");
		http.begin(url_target);
		M5.Lcd.print("[HTTP] POST...\n");
		int httpCode = http.POST((uint8_t*)data_json, strlen(data_json));
		if(httpCode > 0) {
			M5.Lcd.printf("[HTTP] POST... code: %d\n", httpCode);

			if(httpCode == HTTP_CODE_OK) {
				String payload = http.getString();
				M5.Lcd.println(payload);
				Serial.println(payload);
				}
			}else {
			M5.Lcd.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
			}
		http.end();
	}
	else
		{
		M5.Lcd.print("connect failed");
		}

    doc.clear();
}

// ---------------------------------------------------------------

シリアルポートの受信は次のコマンドで行います。

cu -s 115200 -l /dev/ttyUSB0

Arduino 2.1.1 で表示した様子
image.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?