4
3

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にCAT-Mモジュールをつないでhttpsで通信する

Posted at

用意するもの

  • M5Stack
  • CAT-Mモジュール
  • SIMカード
  • 通信先

使うライブラリ

  • TinyGSM

コード例

証明書だなんだかんだを用意しなくていいので楽。
ambient.ioにjsonを送ります。

#include <ArduinoJson.h>
#include <ArduinoHttpClient.h>
#define TINY_GSM_MODEM_SIM7080

#define APN "soracom.ioとか"
#define USER "SIMカードによる"
#define PASS "SIMカードによる"

const char server[] = "ambidata.io";
const char channelId[] = "***";
const char writeKey[] = "***";
char resource[1024];
int port = 443;

#include <TinyGsmClient.h>
TinyGsm modem(Serial1);
TinyGsmClientSecure client(modem);

HttpClient http(client, server, port);
int statusCode = 0;

const int capacity = JSON_OBJECT_SIZE(5);
StaticJsonDocument<capacity> doc;
char payload[2048];
Serial1.begin(115200, SERIAL_8N1, 32, 26); //3番目と4番目の引数はCAT-Mモジュールとの通信で使うポートのRXとTX
modem.restart();

sprintf(resource, "/api/v2/channels/%s/data", channelId);

while (!modem.waitForNetwork() && !modem.isNetworkConnected())
{
  delay(1);
}
SerialBT.printf("APN: %s\n", APN);

modem.gprsConnect(APN, USER, PASS);
while (!modem.isGprsConnected())
{
 delay(1);
}
Serial.printf("Operator: %s\n", modem.getOperator().c_str());

http.connectionKeepAlive(); // ここがポイントらしい
int err = http.post(resource, "application/json", payload);
if (err != 0)
{
  Serial.println("Failed to Connect");
}
statusCode = http.responseStatusCode();
if (statusCode == 200)
{
  Serial.println("Success!");
}
else
{
  Serial.printf("Failed, StatusCode: %d\n", statusCode);
}
Serial.println("Disconnect from Network");
http.stop();
client.stop();
modem.gprsDisconnect();
modem.poweroff();

接続を生かしておくか、モデムの電源まで切るかはお好みで。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?