0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ESP32: GATT で String を送信

Last updated at Posted at 2024-09-24

こちらのプログラムを改造して、String を送信するようにしました。
ESP32: GATT通信 (ArduinoBLE.h)

プログラム

string_send.ino
// ---------------------------------------------------------------
/*
	string_send.ino

					Sep/24/2024
*/
// ---------------------------------------------------------------
#include <ArduinoBLE.h>
#define	PROGRAM	"string_send.ino"
#define	VERSION	"2024-9-24 PM 14:49"

BLEService batteryService("180F");

BLECharacteristic batteryLevelChar("2A19", BLERead | BLENotify,
		"012345678901234567890123456789");

int icount = 0;
// ---------------------------------------------------------------
void setup() {
	Serial.begin(115200);
	while (!Serial);

	if (!BLE.begin()) {
		Serial.println("starting BLE failed!");
		while (1);
	}

	BLE.setLocalName("BatteryMonitor");
	BLE.setAdvertisedService(batteryService); // add the service UUID
	batteryService.addCharacteristic(batteryLevelChar); // add the battery level characteristic
	BLE.addService(batteryService);

	// 初期値を設定
//	batteryLevelChar.writeValue("Battery: 0");

	BLE.advertise();

	Serial.println("Bluetooth® device active, waiting for connections...");

	delay(2000);
	Serial.println(PROGRAM);
	Serial.println(VERSION);
	Serial.println("*** setup end ***");
}

// ---------------------------------------------------------------
void loop() {
	if ((icount % 200) == 0)
		{
		Serial.print("*** loop *** ");
		Serial.println(icount);
		}
	icount++;
	delay(10);
	// wait for a Bluetooth® Low Energy central
	BLEDevice central = BLE.central();

	// if a central is connected to the peripheral:
	if (central) {
		if (central.connected()) {
			updateBatteryLevel();
		}
	}
}

// ---------------------------------------------------------------
void updateBatteryLevel() {
	int batteryLevel = 25 + icount;

	// 文字列を作成して送信
	String str_out = "Battery: " + String(batteryLevel);
	batteryLevelChar.writeValue(str_out.c_str());
}
// ---------------------------------------------------------------

Android の LightBlue で受信

Data format を UTF-8 String にします。

LightBlue_sep24.png

参考

Assigned Numbers

次のように定義されています。

Battery Service 0x180F
Battery Level 0x2A19

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?