#5 Arduino Nano 33 BLE - Send data from mobile over Bluetooth and print it over UART

#5 Arduino Nano 33 BLE - Send data from mobile over Bluetooth and print it over UART


To send and receive data between the UART and BLE connection, Nordic UART Service (NUS)  is used. So, on a Arduino Nano BLE 33, if we want to receive data over Bluetooth from mobile phone and print the same over UART, this service has to be used. NUS acts a bridge between the serial port and wireless section.

Mobile Phone is a Central device which connects to the Peripheral which is a Nordic board here. The Nordic board advertises continuously and then waits for the connection to Central device. The advertising happens on the 3 advertising channels that are out of 40 channels.

Below is the code for receiving data from BLE and printing over UART

#include <ArduinoBLE.h>

BLEService uartService("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); // Custom UART service
BLECharacteristic rxChar("6E400002-B5A3-F393-E0A9-E50E24DCCA9E",
                         BLEWrite | BLEWriteWithoutResponse, 512);

void setup() {
  Serial.begin(115200);
  while (!Serial);

  // Start BLE
  if (!BLE.begin()) {
    Serial.println("BLE start failed!");
    while (1);
  }

  Serial.println("BLE UART Receiver Started");
 
  // Advertise the service
  BLE.setLocalName("Nano33BLE_UART");
  BLE.setAdvertisedService(uartService);
  uartService.addCharacteristic(rxChar);
  BLE.addService(uartService);

  BLE.advertise();
  Serial.println("Waiting for BLE connection...");
}

void loop() {
  BLEDevice central = BLE.central();

  if (central) {
    Serial.print("Connected to Central device");
    //Serial.println(central.address());

    while (central.connected()) {

      if (rxChar.written()) {

    const uint8_t* data = rxChar.value();   // raw bytes
    int len = rxChar.valueLength();         // number of bytes received

    if (len > 0) {
      char buffer[513];

      // copy bytes to char buffer
      for (int i = 0; i < len; i++) {
        buffer[i] = (char)data[i];
      }

      buffer[len] = '\0';   // null terminate

      String incoming = buffer;

      Serial.print("Received: ");
      Serial.println(incoming);
    }
}
    }

    Serial.println("Disconnected");
  }
}

Explanation of this project in the below video


Post a Comment

0 Comments