手順3 BLEをつかってみよう
次に、M5Stackに標準搭載されているBLEを使ってみます。
プログラム
ESP32のサンプルスケッチ「BLE_notify」を利用して動作を確認してみましょう。M5StackのBLEがスマートフォンなどに接続されたときにLチカするプログラムです。
//ライブラリーは下記のようにインクルードします
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <M5Stack.h>
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint8_t value = 0;
//UUID(ユニバーサル固有識別番号)を任意で決め、記述します。
//これはデータを識別するための番号です。
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
//LEDのピンとその状態を指定します
int ledPin = 21;
int ledState = LOW;
//BLEがデバイスと接続されたとき「true」、そうでないとき「false」を変数「deviceConnected」に格納します
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
//BLEを使う設定やM5Stackの設定を記述します
void setup() {
Serial.begin(921600);
M5.begin();
pinMode(ledPin,OUTPUT);
// Create the BLE Device
BLEDevice::init("M5Stack_BLE");
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
// Create a BLE Descriptor
pCharacteristic->addDescriptor(new BLE2902());
// Start the service
pService->start();
// Start advertising
pServer->getAdvertising()->start();
Serial.println("Waiting a client connection to notify...");
}
void loop() {
// notify changed value
// BLEがデバイスと接続したときLEDが点灯します
if (deviceConnected) {
ledState = HIGH;
digitalWrite(ledPin,ledState);
pCharacteristic->setValue(&value, 1);
pCharacteristic->notify();
value++;
delay(10); // bluetooth stack will go into congestion, if too many packets are sent
}
// disconnecting
// BLEがデバイスと接続したときLEDが消灯します
if (!deviceConnected && oldDeviceConnected) {
delay(500); // give the bluetooth stack the chance to get things ready
pServer->startAdvertising(); // restart advertising
Serial.println("start advertising");
oldDeviceConnected = deviceConnected;
ledState = LOW;
digitalWrite(ledPin,ledState);
}
// connecting
if (deviceConnected && !oldDeviceConnected) {
// do stuff here on connecting
oldDeviceConnected = deviceConnected;
}
m5.update();
}
実行結果
実際に動かしてみると以下のようになります。

おわりに
M5StackはESP32をもとにした開発ボードで、Wi-FiやBLEを比較的に簡単に使うことができます。ディスプレイやボタンが標準搭載されており、さらに重ねるだけで拡張できるモジュールも豊富なので機能の追加も容易です。思いついたアイデアをすぐに実行でき、プロトタイピングをしやすい開発ボードとなっています。
そんな魅力あふれるM5Stackで電子工作を始めてみませんか?
