BLE - UART 服务

材料准备

  • AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1

  • Android / iOS smartphone

范例说明

介绍

With BLE, application data is sent and received using the GATT system. GATT uses services, characteristics, and attributes to organise data and control how the data can be read from and written to. The Bluetooth SIG specification for BLE includes several predefined services for common applications, but users are free to implement custom services and characteristics to best fit their data structure and application needs.

在此范例中,BLEService和BLECharacteristic用于实现类似于常规UART传输ASCII字符的自定义服务。此自定义服务是在多个智能手机应用程序中受支持的Nordic UART服务。

流程

确保您的智能手机上已安装兼容的BLE UART应用程序,该应用程序可在以下位置获得:

– Google Play Store: https://play.google.com/store/apps/details?id=com.adafruit.bluefruit.le.connect https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal

– Apple App Store: https://apps.apple.com/us/app/bluefruit-connect/id830125974

Open the example, “Files” “Examples” “AmebaBLE” “BLEUartService”.

../../../../_images/image14.png

Upload the code and press the reset button on Ameba once the upload is finished. Open the app on your smartphone, scan and connect to the Ameba board shown as “AMEBA_BLE_DEV” and choose the UART function in the app. Note that the BLE UART service on the Ameba board will only work with the UART and Plotter functions in the Bluefruit Connect app, other functions (Pin I/O, Image Transfer) require other BLE services that are not included in this example.

../../../../_images/image1-2.png ../../../../_images/image1-3.png

In the UART terminal section of the app, enter a message and click send. You should see the message appear in the Arduino serial monitor. In the Arduino serial monitor, enter a message and click send. The message will appear in the smartphone app.

../../../../_images/image1-4.png ../../../../_images/image51.png

程式码说明

The BLECharacteristic class is used to create two characteristics, one for receive (Rx) and one for transmit (Tx), and added to a service created with the BLEService class. The required read/write/notify properties are set for each characteristic using the set__Property() methods, and callback functions are registered using the set__Callback() methods. The required buffer size is also set for each characteristic so that it has enough memory to store a complete string. When data is written to the receive characteristic, the registered callback function is called, which prints out the received data as a string to the serial monitor. When data is received on the serial port, it is copied into the transmit characteristic buffer, and the notify() method is used to inform the connected device of the new data.