LoginSignup
2
2

More than 3 years have passed since last update.

ESP32のIoTで使えるかもしれない使用例

Last updated at Posted at 2019-12-19

概要

 この記事はArduino Advent Calendar2019 12/20の記事です。
 今更感はあるかとは思いますがGitHub上のespressif/arduino-esp32のライブラリから主要な機能の使用例をコメントの翻訳とともに挙げていきます。

*私自身初心者のためこの記事も初心者向けです。ご容赦願います!

ESP32とは

 espressif社が開発したIoT向けにWiFiやBluetoothなどの機能が実装されているマイコンです。電源やシリアル変換ICなどものっている開発ボードも多く発売されています。

arduino-esp32ライブラリのインストール方法

使用例

概要にも書きました通りGitHubのespressif/arduino-esp32レポジトリのサンプルから使いそうなのを選んでやっていきます。

PWM

モーターやLEDの明滅制御によく使われるPWM(Pulse Width Moduration)制御ですが、このライブラリではPWMというサンプルや関数はありません。そのかわりLEDCというライブラリがあります。今回はGPIOの13番ピンでPWMしてみます。

esp32_pwm.ino
#define pin 13
#define ledc_channel 0

void setup() {
  ledcSetup(ledc_channel,1000,8); //LEDCチャネル、周波数、解像度
  ledcAttachPin(pin,ledc_channel);
}

void loop() {
    ledcWrite(ledc_channel,(uint32_t)128); //この解像度ではDuty比50%
}

Digital Analog Converter(DAC)

DACは25番ピン、26番ピンのみ使用できます。dacWrite関数の一つ目の変数にピン番号を、二つ目の変数に0から255の整数を設定します。0が0V出力、255が3.3V出力となります。

esp32_dac.ino
void setup() {
}
void loop() {
 dacWrite(25,254);
 dacWrite(26,200);
}

SimpleWiFiServer

同一ネットワーク上でWEBサーバーとして動作してWEBページからのHTTPリクエストに応じてLEDをON、OFFさせることができます。

ここの記事を参照

Bluetooth(Classic)のシリアル通信

Bluetoothでペアリングした機器からOn;という文字列を送るとGPIO33番ピンがオンして、Off;という文字列を送るとオフするコードです。

esp32_BTserial.ino
#include "BluetoothSerial.h"
#include<string.h>
BluetoothSerial SerialBT;

void setup() {

  Serial.begin(115200);
  SerialBT.begin("esp32");
  pinMode(33,OUTPUT);
}

void loop() {
    String str=SerialBT.readStringUntil(';');
    if(str=="On")digitalWrite(33,HIGH);
    else if(str=="Off") digitalWrite(33,LOW);
  delay(10);
}

NTPサーバーから時刻を取得してRTCを動かす

1秒ごとに現在時刻をシリアルに表示します。

esp32_ntp.ino
#include <WiFi.h>
#include "time.h"

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

const char* ntpServer="0.jp.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,"%Y %m %d %H:%M:%S");
}

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

  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

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

まとめ

 すべての機能を網羅することはできませんが、わたしがIoTデバイスっぽいものを作る過程で習得した機能を同じ初心者がとっかかりやすいやすいように使えそうな機能を中心にまとめてみました。お役に立てていただけたら幸いです。

2
2
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
2
2