BLE - UART 服務

材料準備

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

  • Android / iOS 智能手機

範例説明

介紹

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.