ESP32にPlatformIO IDEをつかって書き込む話


はじめに

普段マイコンの書き込みにはArudino IDEを使ったり同サイト内のWeb Editorを使ったりしていたが…
アプリのほうは個人的に使いづらい
Web Editorはクラウド型なので便利で使いやすいけどログインの処理とかが面倒くさい
みたいなことを感じてたので今回KeeYees ESP32 ESP-32S 開発ボードをAmazonで衝動的にポチッたついでにVSCode + PlatformIOでサンプルプログラムを書き込んでみた

環境

OSはwindows
VSCodeとPlatformIOはインストール済み

サンプルプログラム

SimpleTime.cpp
#include <WiFi.h>
#include "time.h"

const char* ssid       = "your_ssid";
const char* password   = "your_pass";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

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

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
}

サンプルプログラムにはwifiにつなげて時間を表示するプログラムを選択

手順

PlatformIOはVSコードからわりかし簡単にインストールできる

が+New Projectのときのボード選択ありすぎ...どれだこれ?
とりあえずesp32devを選択
platfomは02:espressif8266と32:espressif32で分かれているので注意が必要かも今は大体WROOM-32が販売してるとおもうのでespressif8266は使わないかな?

プログラムをの名前は適当に入力

先ほどのサンプルプログラムをsrcの中のmain.cppに入力

platformio.ini内にモニタースピードとアップロードスピードを設定

platformio.ini
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
upload_speed = 921600

モニタースピードは入れないと表示が文字化けするし
アップロードスピードは自分の環境だといれないと書き込みがタイムアウトで失敗することが多かった

VSCodeの左下のバーから
✓:build
→:uploadをおこなう

無事成功したらserialmonitorから結果が見れます

まとめ

数回PlatformIOは触ったことがあったがやっぱり純正より使いやすいしカッコいい(笑)
つぎはこの開発環境とESP32で温度検知をやってみようとおもった