SerialToSerialBT

はじめに

シリアルコンソールとBluetoothコンソールの間でデータ(文字)を送受信します。

動作確認は、ESP32 2.0.2のときのものです。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Evandro Copercini - 2018
//
//This example creates a bridge between Serial and Classical Bluetooth (SPP)
//and also demonstrate that SerialBT have the same functionalities of a normal Serial

#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif

BluetoothSerial SerialBT;
 

SerialBTを、BluetoothSerialクラスの変数として定義します。

setup()

19
20
21
22
23
24
void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");
}
 

SerialBT.begin()を使って、Bluetoothデバイス名を設定します。この場合、「ESP32test」が設定されます。この名前が、PC等に表示されます。

loop()

25
26
27
28
29
30
31
32
33
void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

Arduinoのシリアルコンソールに入力があればデータを読み取り、SerialBT.write()を使って、Bluetoothデバイスに送信します。

SerialBT.available()は、Bluetoothデバイスから読み取り可能なバイト数(文字数)を取得する関数です。0以上の場合、SerialBT.read()を使い、Bluetoothデバイスから1文字読み取り、シリアルコンソールに送信します。

実験結果

Windows10上で、実際に試してみました。端末ソフトにはTera Termを利用しました。

まずは、Windows10とESP32のペアリングを行います。その後、Arduinoのシリアルコンソールと、Tera Termとを起動します。

左側が、Arduinoのシリアルコンソール、右側が、Bluetoothデバイスに接続したTera Termのコンソールです。

区別がわかりづらいですが、“From Arduino"がArduino(COM4)から送信した文字列です。送信ボタンを押すと、表示が消えてしまうので、Arduinoコンソールには何も残りません。 “From Tera Term"が、Tera Termから送信した文字列です。Tera Termのローカルエコーを有効にしたので、Tera Termにも表示されています。

バージョン

Hardware:ESP-WROOM-32
Software:Arduino core for the ESP32 2.0.4

最終更新日

September 4, 2022

inserted by FC2 system