Zum Hauptinhalt springen

Bluetooth serial

What this example shows​

Exchange text between the Inkplate 10 and a phone over Bluetooth. The sketch starts a Bluetooth Low Energy (BLE) UART-style service. The board advertises as Inkplate 10. Text that the phone writes to the board is printed in the Serial Monitor, and text you type in the Serial Monitor is sent to the connected phone.

Use a phone app that can talk to a BLE UART service. The example header suggests a Bluetooth serial terminal app such as Serial Bluetooth Terminal.

Example code​

Upload the sketch, open the Serial Monitor at 115200 baud, then connect to Inkplate 10 from your phone app. In the Arduino IDE, choose the Inkplate 10 board under Tools, Board, Inkplate Boards before you upload.

Select Board
Inkplate10_Bluetooth_Serial.ino
// Next 3 lines are a precaution, you can ignore those, and the example would also work without them
#if !defined(ARDUINO_INKPLATE10) && !defined(ARDUINO_INKPLATE10V2)
#error \
"Wrong board selection for this example, please select e-radionica Inkplate10 or Soldered Inkplate10 in the boards menu."
#endif

// Include Inkplate and BLE libraries to the sketch
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include "Inkplate.h"

// BLE UART service UUID and RX/TX characteristics for serial-style communication over Bluetooth LE
#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" // For data coming IN to Inkplate
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" // For data coming OUT from Inkplate

Inkplate inkplate(INKPLATE_1BIT); // Create an object on Inkplate library and also set library into 1-bit mode (BW)

BLEServer *pServer = NULL; // Pointer to BLEServer
BLECharacteristic *pTxCharacteristic; // Pointer to TX characteristic
bool deviceConnected = false; // Is client currently connected
bool oldDeviceConnected = false; // Store the previous connection

// Connect/Disconnect callback
class MyServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer *pServer)
{
deviceConnected = true;
Serial.println("Device connected");
};

void onDisconnect(BLEServer *pServer)
{
deviceConnected = false;
Serial.println("Device disconnected");
}
};

// On receive callback
class MyCallbacks : public BLECharacteristicCallbacks
{
void onWrite(BLECharacteristic *pCharacteristic)
{
String rxValue = pCharacteristic->getValue();

if (rxValue.length() > 0)
{
Serial.print("Received Value: ");
for (int i = 0; i < rxValue.length(); i++)
{
Serial.print(rxValue[i]);
}
Serial.println();
}
}
};

void setup()
{
inkplate.begin(); // Init Inkplate library (you should call this function ONLY ONCE)
inkplate.clearDisplay(); // Clear frame buffer of display
inkplate.setTextSize(4); // Scale text to be 5 times bigger then original (5x7 px)

// Display initial text
inkplate.setTextColor(BLACK);
inkplate.println("Bluetooth Serial");
inkplate.println("Example");
inkplate.println();
inkplate.setTextSize(3);

// Init serial communication
Serial.begin(115200);
// Create the BLE Device
BLEDevice::init("Inkplate 10");

// 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 (TX)
pTxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY);

// Let client turn On/Off notifications for this characteristic (needed for ESP32 BLE)
// NOTE: Descriptor 2902 is not required when using NimBLE as it is automatically added based on the characteristic properties
pTxCharacteristic->addDescriptor(new BLE2902());

// Create a BLE Characteristic (RX)
BLECharacteristic *pRxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);

// Assign a callback handler
pRxCharacteristic->setCallbacks(new MyCallbacks());

// Start the service
pService->start();

// Start advertising
pServer->getAdvertising()->start();

// Check if Bluetooth controller is enabled
if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED)
{
Serial.println("BLE controller failed to start");
inkplate.println("BLE FAILED");
}
else
{
// Bluetooth started successfully, print the messages on the screen
inkplate.println("The device started, now you can ");
inkplate.println("pair it with Bluetooth and send");
inkplate.println("messages.");
inkplate.println();
inkplate.println("Open Serial Monitor at 115200");
inkplate.println("baud!");
}

// Update the display
inkplate.display();
}

void loop()
{
// If Bluetooth is connected, check for available data on Serial and send that data via Bluetooth to the connected device
if (deviceConnected)
{
if (Serial.available())
{
String s = Serial.readStringUntil('\n') + "\n"; // Load the message from serial
Serial.printf("Sent value: %s\n", s.c_str());
pTxCharacteristic->setValue((uint8_t *)s.c_str(), strlen(s.c_str())); // Convert the message into bytes
pTxCharacteristic->notify(); // Transmit the message
}
}

// When a client disconnects, restart BLE advertising so that we can accept new connections
if (!deviceConnected && oldDeviceConnected)
{
delay(500); // Allow bluetooth stack some time
pServer->startAdvertising(); // Restart advertising
oldDeviceConnected = false; // Update state
}

// Detect new connections
if (deviceConnected && !oldDeviceConnected)
{
// Do stuff here on connecting...
oldDeviceConnected = true; // Update the old state
}
}

Trimmed from Inkplate10_Bluetooth_Serial.ino: the file header comment is left out. The code is otherwise unchanged.

Functions used​

Inkplate(uint8_t mode)returns None

Creates the Inkplate object and chooses the display mode. `INKPLATE_1BIT` is black and white and supports partial updates. `INKPLATE_3BIT` is grayscale and only supports full updates.

ReturnsConstructor; no return value.

Parameters

TypeNameDescription
uint8_tmodeDisplay mode: INKPLATE_1BIT (0) or INKPLATE_3BIT (1).
inkplate.begin()returns void

Initializes the library, the peripherals and the frame buffers. Call it once in `setup()`, later calls are ignored.

ReturnsNothing.

inkplate.clearDisplay()returns void

Clears the frame buffer in memory. It does not clear the panel itself, call `display()` afterwards to do that.

ReturnsNothing.

inkplate.setTextSize(uint8_t s)returns void

Sets the text magnification. Size 1 is the classic 5x7 pixel font, size 5 is five times bigger. This comes from the Adafruit GFX base class that the library builds on.

ReturnsNothing.

Parameters

TypeNameDescription
uint8_tsText size multiplier.
inkplate.setTextColor(uint16_t c)returns void

Sets the text color with a transparent background. This comes from the Adafruit GFX base class that the library builds on.

ReturnsNothing.

Parameters

TypeNameDescription
uint16_tcText color, for example BLACK.
inkplate.println(value, format)returns size_t

Same as `print()`, then moves the cursor to the start of the next line.

ReturnsNumber of bytes printed.

Parameters

TypeNameDescription
text, char or numbervalueWhat to print. Optional: with no value it only moves to the next line.
intformatOptional. Number base for integers, for example DEC.
Serial.begin(unsigned long baud)returns void

Starts the serial connection to the computer. Set the Serial Monitor to the same baud rate.

ReturnsNothing.

Parameters

TypeNameDescription
unsigned longbaudBaud rate. The sketch uses 115200.
BLEDevice::init(name)returns void

Starts the Bluetooth LE stack and sets the name the board advertises. The sketch passes the name Inkplate 10. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsNothing.

Parameters

TypeNameDescription
textnameDevice name shown to other devices.
BLEDevice::createServer()returns BLEServer *

Creates the BLE server that phones connect to. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsPointer to the new server, which the sketch keeps in `pServer`.

BLEServer::setCallbacks(BLEServerCallbacks *pCallbacks)returns void

Registers the object whose `onConnect()` and `onDisconnect()` functions run when a phone connects or disconnects. In this sketch they set the `deviceConnected` flag and print a line to Serial. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsNothing.

Parameters

TypeNameDescription
BLEServerCallbacks *pCallbacksCallback object. The sketch passes new MyServerCallbacks().
BLEServer::createService(uuid)returns BLEService *

Creates a BLE service on the server. The sketch uses the UART service UUID defined at the top of the file. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsPointer to the new service.

Parameters

TypeNameDescription
textuuidUUID of the service. The sketch passes SERVICE_UUID.
BLEService::createCharacteristic(uuid, properties)returns BLECharacteristic *

Adds a characteristic to the service. The sketch creates two: a TX characteristic with the `PROPERTY_NOTIFY` property for data going out of the Inkplate, and an RX characteristic with the `PROPERTY_WRITE` property for data coming in. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsPointer to the new characteristic.

Parameters

TypeNameDescription
textuuidUUID of the characteristic: CHARACTERISTIC_UUID_TX or CHARACTERISTIC_UUID_RX.
uint32_tpropertiesWhat a connected device may do with it, for example BLECharacteristic::PROPERTY_NOTIFY or BLECharacteristic::PROPERTY_WRITE.
BLECharacteristic::addDescriptor(BLEDescriptor *pDescriptor)returns void

Adds a descriptor to the characteristic. The sketch adds a `BLE2902` descriptor to the TX characteristic, which lets the phone turn notifications on and off. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsNothing.

Parameters

TypeNameDescription
BLEDescriptor *pDescriptorDescriptor to add. The sketch passes new BLE2902().
BLECharacteristic::setCallbacks(BLECharacteristicCallbacks *pCallbacks)returns void

Registers the object whose `onWrite()` function runs when the phone sends data. In this sketch it prints the received text to Serial. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsNothing.

Parameters

TypeNameDescription
BLECharacteristicCallbacks *pCallbacksCallback object. The sketch passes new MyCallbacks().
BLEService::start()returns void

Starts the service so devices can use it. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsNothing.

BLEServer::getAdvertising()returns BLEAdvertising *

Returns the advertising object of the server. The sketch calls `start()` on it to begin advertising, which makes the board visible to phones. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsPointer to the advertising object.

esp_bt_controller_get_status()returns esp_bt_controller_status_t

Returns the state of the Bluetooth controller. The sketch compares it with `ESP_BT_CONTROLLER_STATUS_ENABLED` to see whether Bluetooth started. It comes from the ESP32 Arduino core, not from the Inkplate library.

ReturnsController status.

inkplate.display(bool _leaveOn = 0)returns void

Refreshes the whole panel from the frame buffer (a full update).

ReturnsNothing.

Parameters

TypeNameDescription
bool_leaveOnIf true, the e-paper supply stays on after the update, which saves time on the next update. Defaults to 0.
BLECharacteristic::getValue()returns String

Returns the data the phone last wrote to the characteristic. The sketch calls it inside `onWrite()`. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsThe received text.

Serial.print(value, format)returns size_t

Prints text or a number to the Serial Monitor without a line break.

ReturnsNumber of bytes printed.

Parameters

TypeNameDescription
text or numbervalueWhat to print.
intformatOptional. Number base for integers, for example HEX.
Serial.println(value, format)returns size_t

Prints text or a number to the Serial Monitor, followed by a line break.

ReturnsNumber of bytes printed.

Parameters

TypeNameDescription
text or numbervalueWhat to print.
intformatOptional. Number base for integers, for example HEX.
Serial.available()returns int

Returns how many bytes are waiting in the serial receive buffer.

ReturnsNumber of bytes available to read.

Serial.readStringUntil(char terminator)returns String

Reads characters from the serial buffer until the terminator character arrives.

ReturnsThe text read, without the terminator.

Parameters

TypeNameDescription
charterminatorCharacter that ends the text. The sketch passes the newline character.
Serial.printf(const char *format, ...)returns size_t

Prints formatted text to the Serial Monitor, like `printf` in C.

ReturnsNumber of bytes printed.

Parameters

TypeNameDescription
const char *formatFormat string. The sketch prints Sent value: %s followed by a newline.
...argumentsValues for the format string.
BLECharacteristic::setValue(uint8_t *data, size_t length)returns void

Sets the data that the next `notify()` call sends to the phone. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsNothing.

Parameters

TypeNameDescription
uint8_t *dataBytes to send.
size_tlengthNumber of bytes.
BLECharacteristic::notify()returns void

Sends the current value of the characteristic to the connected phone. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsNothing.

BLEServer::startAdvertising()returns void

Restarts advertising. The sketch calls it after a phone disconnects, so a new connection can be made. It comes from the ESP32 Arduino BLE library, not from the Inkplate library.

ReturnsNothing.

delay(unsigned long ms)returns void

Arduino function that pauses the sketch.

ReturnsNothing.

Parameters

TypeNameDescription
unsigned longmsTime to wait, in milliseconds.

What to expect​

The screen shows Bluetooth Serial Example and, once Bluetooth has started, a short instruction ending with Open Serial Monitor at 115200 baud!. If the Bluetooth controller does not start, it shows BLE FAILED.

Serial MonitorAutoscrollShow timestampNewline115200 baud
Message (Enter to send message to the board)
Device connected
Received Value: <text from the phone>
Sent value: <text you typed>
Device disconnected

The placeholder <text from the phone> and <text you typed> stand for your own messages. If Bluetooth fails to start, the Serial Monitor shows BLE controller failed to start. After a phone disconnects, the sketch starts advertising again so you can reconnect.