T-vK / ESP32-BLE-Keyboard

Bluetooth LE Keyboard library for the ESP32 (Arduino IDE compatible)
2.28k stars 379 forks source link

Use BLE-Keyboard with device name from Preferences #224

Closed joostbijl closed 1 year ago

joostbijl commented 1 year ago

Hi,

I'd like to store the device name of my BT Keyboard using the Preferences library. This way, i can change the name and persist during reboots.

I'm probably missing something, but it looks like Arduino won't let you call functions outside the setup() and loop() functions. Yet i want to call the Preferences library to fetch the device name. My assumption is that you want to declare the BleKeyboard object in the main arduino code (not inside the setup() or loop() since they'd be local to those functions).

So this does not work because I can't call preferences.begin() for example.

#include <Preferences.h>
#include <BleKeyboard.h>

Preferences preferences;
preferences.begin("myapp", false);
String btname = preferences.getString("btname", "keyboard");
BleKeyboard bleKeyboard(btname);

void setup() {
  ..
}
void loop() {
 ..
}

This does not work, because I can't use the blekeyboard object from the loop()

#include <Preferences.h>
#include <BleKeyboard.h>

Preferences preferences;

void setup() {
  preferences.begin("myapp", false);
  String btname = preferences.getString("btname", "keyboard");
  BleKeyboard bleKeyboard(btname);
  ..
}
void loop() {
 ..
}

I'm probably lacking some basic Arduino skills, but can someone point me in the right direction?

joostbijl commented 1 year ago

Ok, i fixed it:

#include <Preferences.h>
#include <BleKeyboard.h>

Preferences preferences;
BleKeyboard bleKeyboard("keyboard");

void setup() {
  preferences.begin("myapp", false);
  String btname = preferences.getString("btname", "keyboard");
  bleKeyboard.setName(btname.c_str());
  bleKeyboard.begin();
  ..
}
void loop() {
 ..
}