Arduino as bluetooth keyboard

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Bluetooth LE Keyboard library for the ESP32 (Arduino IDE compatible)

T-vK/ESP32-BLE-Keyboard

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

ESP32 BLE Keyboard library

This library allows you to make the ESP32 act as a Bluetooth Keyboard and control what it does.
You might also be interested in:

  • Send key strokes
  • Send text
  • Press/release individual keys
  • Media keys are supported
  • Read Numlock/Capslock/Scrolllock state
  • Set battery level (basically works, but doesn’t show up in Android’s status bar)
  • Compatible with Android
  • Compatible with Windows
  • Compatible with Linux
  • Compatible with MacOS X (not stable, some people have issues, doesn’t work with old devices)
  • Compatible with iOS (not stable, some people have issues, doesn’t work with old devices)
  • (Make sure you can use the ESP32 with the Arduino IDE. Instructions can be found here.)
  • Download the latest release of this library from the release page.
  • In the Arduino IDE go to «Sketch» -> «Include Library» -> «Add .ZIP Library. » and select the file you just downloaded.
  • You can now go to «File» -> «Examples» -> «ESP32 BLE Keyboard» and select any of the examples to get started.
/** * This example turns the ESP32 into a Bluetooth LE keyboard that writes the words, presses Enter, presses a media key and then Ctrl+Alt+Delete */ #include BleKeyboard.h> BleKeyboard bleKeyboard; void setup() < Serial.begin(115200); Serial.println("Starting BLE work!"); bleKeyboard.begin(); > void loop() < if(bleKeyboard.isConnected()) < Serial.println("Sending 'Hello world'. "); bleKeyboard.print("Hello world"); delay(1000); Serial.println("Sending Enter key. "); bleKeyboard.write(KEY_RETURN); delay(1000); Serial.println("Sending Play/Pause media key. "); bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE); delay(1000); // // Below is an example of pressing multiple keyboard modifiers // which by default is commented out. //  /* Serial.println("Sending Ctrl+Alt+Delete. "); bleKeyboard.press(KEY_LEFT_CTRL); bleKeyboard.press(KEY_LEFT_ALT); bleKeyboard.press(KEY_DELETE); delay(100); bleKeyboard.releaseAll(); */ > Serial.println("Waiting 5 seconds. "); delay(5000); >

The BleKeyboard interface is almost identical to the Keyboard Interface, so you can use documentation right here: https://www.arduino.cc/reference/en/language/functions/usb/keyboard/

Just remember that you have to use bleKeyboard instead of just Keyboard and you need these two lines at the top of your script:

#include BleKeyboard bleKeyboard; 

In addition to that you can send media keys (which is not possible with the USB keyboard library). Supported are the following:

  • KEY_MEDIA_NEXT_TRACK
  • KEY_MEDIA_PREVIOUS_TRACK
  • KEY_MEDIA_STOP
  • KEY_MEDIA_PLAY_PAUSE
  • KEY_MEDIA_MUTE
  • KEY_MEDIA_VOLUME_UP
  • KEY_MEDIA_VOLUME_DOWN
  • KEY_MEDIA_WWW_HOME
  • KEY_MEDIA_LOCAL_MACHINE_BROWSER // Opens «My Computer» on Windows
  • KEY_MEDIA_CALCULATOR
  • KEY_MEDIA_WWW_BOOKMARKS
  • KEY_MEDIA_WWW_SEARCH
  • KEY_MEDIA_WWW_STOP
  • KEY_MEDIA_WWW_BACK
  • KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION // Media Selection
  • KEY_MEDIA_EMAIL_READER

There is also Bluetooth specific information that you can set (optional): Instead of BleKeyboard bleKeyboard; you can do BleKeyboard bleKeyboard(«Bluetooth Device Name», «Bluetooth Device Manufacturer», 100); . (Max lenght is 15 characters, anything beyond that will be truncated.)
The third parameter is the initial battery level of your device. To adjust the battery level later on you can simply call e.g. bleKeyboard.setBatteryLevel(50) (set battery level to 50%).
By default the battery level will be set to 100%, the device name will be ESP32 Bluetooth Keyboard and the manufacturer will be Espressif .
There is also a setDelay method to set a delay between each key event. E.g. bleKeyboard.setDelay(10) (10 milliseconds). The default is 8 .
This feature is meant to compensate for some applications and devices that can’t handle fast input and will skip letters if too many keys are sent in a small time frame.

The NimBLE mode enables a significant saving of RAM and FLASH memory.

Comparison (SendKeyStrokes.ino at compile-time)

RAM: [= ] 9.3% (used 30548 bytes from 327680 bytes) Flash: [======== ] 75.8% (used 994120 bytes from 1310720 bytes) 

NimBLE mode

RAM: [= ] 8.3% (used 27180 bytes from 327680 bytes) Flash: [==== ] 44.2% (used 579158 bytes from 1310720 bytes) 

Comparison (SendKeyStrokes.ino at run-time)

Standard NimBLE mode difference
ESP.getHeapSize() 296.804 321.252 + 24.448
ESP.getFreeHeap() 143.572 260.764 + 117.192
ESP.getSketchSize() 994.224 579.264 — 414.960

How to activate NimBLE mode?

Uncomment the first line in BleKeyboard.h

Change your platformio.ini to the following settings

lib_deps = NimBLE-Arduino build_flags = -D USE_NIMBLE

Credits to chegewara and the authors of the USB keyboard library as this project is heavily based on their work!
Also, credits to duke2421 who helped a lot with testing, debugging and fixing the device descriptor! And credits to sivar2311 for adding NimBLE support, greatly reducing the memory footprint, fixing advertising issues and for adding the setDelay method.

About

Bluetooth LE Keyboard library for the ESP32 (Arduino IDE compatible)

Источник

Как сделать беспроводную Bluetooth клавиатуру на ESP32

Обычно решение задачи создания самодельных средств ввода (клавиатура, мышь, геймпад) для ПК решается на специально предназначенных для этого платах — Arduino Leonardo. На моем канале есть несколько реализованных проектов на этой платформе: самодельный руль и велотренажёр предназначенные для игры в авто или вело симуляторы.

Arduino Leonardo отличается от всех предыдущих плат тем, что микроконтроллер ATmega32u4 имеет встроенный интерфейс USB. С точки зрения компьютера Arduino Leonardo является HID устройством (вроде клавиатуры или мыши), поэтому сделать на основе Arduino Leonardo новый компьютерный эмулятор проще, чем с другими платами.

Однако вышедшая 6 сентября 2016 плата ESP32, имеет на борту не только Wi-Fi но и Bluetooth. А это означает, что можно «запилить» беспроводные:

В этой статье разберем пример создания беспроводной клавиатуры.

Для начала необходимо скачать и установить библиотеку:
(будет в архиве с примерами из этой статьи)

У библиотеки богатый функционал:

  • Отправить нажатия клавиш
  • Послать текст
  • Нажать / отпустить отдельные клавиши
  • Поддерживаются медиа-клавиши
  • Чтение состояния Numlock / Capslock / Scrolllock
  • Отображения уровня заряда (в основном работает, но не отображается в строке состояния Android)
  • Совместим с Android
  • Совместимость с Windows
  • Совместим с Linux
  • Совместим с MacOS X (нестабильно, у некоторых возникают проблемы, не работает со старыми устройствами)
  • Совместимость с iOS (нестабильна, у некоторых возникают проблемы, не работает со старыми устройствами)

Для тестирования соберем макет и напишем несколько примеров. Потребуется: плата ESP32 WROOM DevKit v1, две кнопки и макетная плата.

Если у вас не ноутбук, а стационарный ПК, то еще и bluetooth адаптер.

Первый пример простой. Если клавиатура подключена к ПК, встроенный светодиод горит, если нет — то не горит. bleKeyboard.isConnected()

После загрузки скетча идем в Windows, и добавляем устройство.

Встроенный в плату ESP32 светодиод светится, можно двигаться дальше.

Все функции библиотеки аналогичны Ардуиновским, так что если у Вас есть готовый проект проводной клавиатуры на Arduino, его легко можно сделать беспроводным переписав только «шапку» программы подменив библиотеку и метод создания объекта.

Разберем несколько примеров работы с библиотекой. Метод press() нажимает клавишу, метод releaseAll() отпускает все клавиши.

Для нажатий Ctrl, Alt, ENTER и других функциональных клавиш существует специальная таблица модификаторов:

Вот пример нажатия клавиши ENTER

Реализацию нажатий сочетаний клавиш, можно реализовать следующим способом:

Получилось универсальное устройство для написания любых статей, курсовых и дипломных работ:

  • кнопка BT1 копирует информацию в буфер обмена
  • кнопка BT2 вставляет информацию из буфера обмена

Набор текста осуществляется следующим образом.

Библиотека поддерживает работу с мультимедийными клавишами

Существует также специальная информация Bluetooth, которую вы можно установить при создании объекта клавиатура(необязательно):

  • Вместо BleKeyboard bleKeyboard;
  • BleKeyboard bleKeyboard(«Bluetooth Device Name», «Bluetooth Device Manufacturer», 100); (Максимальная длина — 15 символов, все остальное будет усечено.)

Третий параметр — это начальный уровень заряда батареи вашего устройства. Чтобы отрегулировать уровень заряда батареи позже, вы можете просто отправить команду, например:

По умолчанию уровень заряда батареи установлен на 100%, имя устройства ESP32 Bluetooth Keyboard и производитель Espressif.
Также существует setDelayметод установки задержки между каждым ключевым событием. Например:

bleKeyboard.setDelay(10) — 10 миллисекунд. (по умолчанию это 8.)

Эта функция предназначена для компенсации некоторых приложений и устройств, которые не могут обрабатывать быстрый ввод и будут пропускать буквы, если за короткий промежуток времени будет отправлено слишком много ключей.

Все функции библиотеки работают как нужно, а Arduino Leonardo пожалуй можно отправлять на свалку истории, особенно учитывая то, что ESP32 стоит дешевле даже Китайской реплики платы Arduino Leonardo, не говоря уже о фирменных платах Arduino.

Источник

Читайте также:  Can you bluetooth android to apple
Оцените статью
Adblock
detector