Help with the Arduino BLE

Hello, I am trying to connect my 2 Arduino Nanos BLE to each other. The current setup is Arduino(1) has a distance sensor, Arduino(2) has a button and LCD screen. I would like to be able to read the distance sensor on Arduino(1) and send the data to Arduino(2) and view the data on the LCD screen. After use a button on Arduino(2) to control a switch on Arduino(1)

Arduino(2) code

#include <ArduinoBLE.h>
BLEService customService("19B10000-E8F2-537E-4F6C-D104768A1214");
BLEUnsignedIntCharacteristic distanceSensor("19b10001-e8f2-537e-4f6c-d104768a1214", BLERead | BLEWrite);
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while(!Serial);
  BLE.begin();
  BLE.setLocalName("COM port7");
  BLE.setAdvertisedService(customService);
  customService.addCharacteristic(distanceSensor);
  BLE.addService(customService);
  BLE.advertise();
  Serial.println("Being advertised");
  Serial.println("Bluetooth® Low Energy Central - Conteol");
  BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");

}

void loop() {
  // put your main code here, to run repeatedly:
    BLEDevice peripheral = BLE.available();
    
  if (peripheral) {
    Serial.print("Found ");
    Serial.print(peripheral.address());
    Serial.print(" '");
    Serial.print(peripheral.localName());
    Serial.print("' ");
    Serial.print(peripheral.advertisedServiceUuid());
    Serial.println();

    if (peripheral.localName() != "COM port5"){
      return;
    }

    BLE.stopScan();

    controlBoard(peripheral);

    BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");
  }
}

void controlBoard(BLEDevice peripheral){
  Serial.println("Connecting ...");

  if (peripheral.connect()){
    Serial.println("Connected");
  } else {
    Serial.println("Failed to connect!");
    return; 
  }

   // discover peripheral attributes
  Serial.println("Discovering attributes ...");
  if (peripheral.discoverAttributes()) {
    Serial.println("Attributes discovered");
  } else {
    Serial.println("Attribute discovery failed!");
    peripheral.disconnect();
    return;
  }
BLECharacteristic distanceSensor = peripheral.characteristic("19b10001-e8f2-537e-4f6c-d104768a1214");
    if (!distanceSensor) {
    Serial.println("Peripheral does not have distanceSensor characteristic!");
    peripheral.disconnect();
    return;
  } else if (!distanceSensor.canWrite()) {
    Serial.println("Peripheral does not have a writable distanceSensor characteristic!");
    peripheral.disconnect();
    return;
  }
  
  while(peripheral.connected()){
    if (distanceSensor.written()) {
        unsigned int value = distanceSensor.readValue();
        Serial.print("Received value: ");
        Serial.println(value);
       }
     }
  Serial.println("Peripheral disconnected");
}

Ardunio(1) code

#include <ArduinoBLE.h>
  long previousMillis = 0; // last time readings were checked, in ms

  unsigned int previousDistance = 0;
  const float UPDATE_FREQUENCY = 2000;

  int trigPin= 12;
  int echoPin= 11;
  float distanceToTarget;
  float pingTravelTime;
  float pingTravelDistance;

  BLEService customService("19B10000-E8F2-537E-4F6C-D104768A1214");
  BLEUnsignedIntCharacteristic BLE_distance("19b10001-e8f2-537e-4f6c-d104768a1214", BLERead | BLEWrite);

void setup() {
Serial.begin(9600);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  while(!Serial);
      if(!BLE.begin()){
      Serial.println("starting Bluetooth® Low Energy module failed!");

      while(1);
    }
  BLE.setLocalName("COM port5");
  BLE.setAdvertisedService(customService);
  //add what you need to send
  customService.addCharacteristic(BLE_distance);
  BLE.addService(customService);
  BLE_distance.setValue(0);
  BLE.advertise();
  Serial.println("Being advertised");
}

void loop() {
  // put your main code here, to run repeatedly:
 BLEDevice central = BLE.central();

  if (central){
    Serial.print("Connected to central: ");
    Serial.println(central.address());

    while (central.connected()){
        long currentMillis = millis();
          
        if (currentMillis - previousMillis >= UPDATE_FREQUENCY) {
          previousMillis = currentMillis;
           updateReadings();
          } 
    }
    Serial.print(F("Disconnected from central: "));
    Serial.println(central.address());
   }
}
 unsigned int getDistance() {
  readValues();
  return (unsigned int) (distanceToTarget);
}
void updateReadings() {
   unsigned int distance = getDistance();
    if (distance != previousDistance){}
    Serial.print("Distance: ");
    Serial.println(distance);
    BLE_distance.writeValue(distance);
    previousDistance = distance;

  }
void readValues(){
    digitalWrite(trigPin,LOW);
    delayMicroseconds(10);
    digitalWrite(trigPin,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin,LOW);
    pingTravelTime=pulseIn(echoPin,HIGH);
    pingTravelDistance=(pingTravelTime*765.*5280.*12.)/(3600.*1000000.);
    distanceToTarget=(pingTravelDistance/2)*100;
}

Welcome to the forum

Your topic was MOVED to its current forum category which is more appropriate than the original as it is not related to IDE version 2.0

i have updated my code hopefully this will make it easier to troubleshoot.
Central Code

#include <ArduinoBLE.h>
BLEService customService("19b10000-e8f2-537e-4f6c-d104768a1214");
BLEUnsignedIntCharacteristic BLE_distance("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
BLEUnsignedIntCharacteristic data("19B10002-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);


void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
  while(!Serial);
    BLE.begin();
    Serial.println("Bluetooth® Low Energy Central");
    BLE.setLocalName("COM port7");
    BLE.setAdvertisedService(customService);
    customService.addCharacteristic(BLE_distance);
    customService.addCharacteristic(data);
    BLE.addService(customService);
    BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");

}

void loop() {
  // put your main code here, to run repeatedly:
  BLEDevice peripheral = BLE.available();

  if (peripheral) {
    // discovered a peripheral, print out address, local name, and advertised service
    Serial.print("Found ");
    Serial.print(peripheral.address());
    Serial.print(" '");
    Serial.print(peripheral.localName());
    Serial.print("' ");
    Serial.print(peripheral.advertisedServiceUuid());
    Serial.println();

    if (peripheral.localName() != "COM port5") {
      return;
    }

    // stop scanning
    BLE.stopScan();

    controlLed(peripheral);

    // peripheral disconnected, start scanning again
    BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");
  }
}

void controlLed(BLEDevice peripheral) {
  // connect to the peripheral
  Serial.println("Connecting ...");

  if (peripheral.connect()) {
    Serial.println("Connected");
  } else {
    Serial.println("Failed to connect!");
    return;
  }

  // discover peripheral attributes
  Serial.println("Discovering attributes ...");
  if (peripheral.discoverAttributes()) {
    Serial.println("Attributes discovered");
  } else {
    Serial.println("Attribute discovery failed!");
    peripheral.disconnect();
    return;
  }

  BLECharacteristic BLE_distance = peripheral.characteristic("19B10001-E8F2-537E-4F6C-D104768A1214");
  BLECharacteristic data = peripheral.characteristic("19B10002-E8F2-537E-4F6C-D104768A1214");



  while(peripheral.connected()) {
   BLE_distance.written();
   Serial.print(F("Received value: "));
   Serial.println(BLE_distance.readValue());
   Serial.println(" Inches");
   delay(2000);
   }

  Serial.println("Peripheral disconnected");


}

peripheral Code

#include <ArduinoBLE.h>
BLEService customService("19b10000-e8f2-537e-4f6c-d104768a1214");
BLEUnsignedIntCharacteristic BLE_distance("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
BLEUnsignedIntCharacteristic data("19B10002-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);

  int trigPin= 12;
  int echoPin= 11;
  float distanceToTarget;
  float pingTravelTime;
  float pingTravelDistance;

  int value;
  long previousMillis = 0;
  unsigned int previousDistance = 0;
  const float UPDATE_FREQUENCY = 2000;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  while(!Serial);
  if (!BLE.begin()) {
    Serial.println("starting Bluetooth® Low Energy module failed!");

    while (1);
        
      }
    BLE.setLocalName("COM port5");
    BLE.setAdvertisedService(customService);
    customService.addCharacteristic(BLE_distance);
    customService.addCharacteristic(data);
    BLE.addService(customService);
    BLE_distance.setValue(0);

    BLE.advertise();
      if(!BLE.advertise()){
        Serial.println("Failed To Advertise");
      }
    
    Serial.println("Being advertised");
  
}

void loop() {
  // put your main code here, to run repeatedly:
  BLEDevice central = BLE.central();

  if (central) {
    Serial.print("Connected to central: ");
    // print the central's MAC address:
    Serial.println(central.address());

    BLE.stopScan();
    sendData(central);
    BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");
  }
  //Serial.println("not connected");
}

void sendData(BLEDevice central){
  Serial.println("Connecting ...");

  if (central.connect()){
    Serial.println("Connected");
  } else {
    Serial.println("Failed to connect!");
    return; 
  }

   // discover Central attributes
  Serial.println("Discovering attributes ...");
  if (central.discoverAttributes()) {
    Serial.println("Attributes discovered");
  } else {
    Serial.println("Attribute discovery failed!");
    central.disconnect();
    return;
  }

  BLECharacteristic BLE_distance = central.characteristic("19B10001-E8F2-537E-4F6C-D104768A1214");
  BLECharacteristic data = central.characteristic("19B10002-E8F2-537E-4F6C-D104768A1214");

    if (!BLE_distance) {
    Serial.println("Central does not have distanceSensor characteristic!");
    central.disconnect();
    return;
  } else if (!BLE_distance.canWrite()) {
    Serial.println("Central does not have a writable distanceSensor characteristic!");
    central.disconnect();
    return;
  }

    if (!data) {
    Serial.println("Central does not have data characteristic!");
    central.disconnect();
    return;
  } else if (!data.canWrite()) {
    Serial.println("Central does not have a writable data characteristic!");
    central.disconnect();
    return;
  }

  while (central.connected()){
  long currentMillis = millis();
          
    if (currentMillis - previousMillis >= UPDATE_FREQUENCY) {
        previousMillis = currentMillis;
      updateReadings();
     }  
    if (data.written()){
      Serial.print("Received value: ");
      Serial.println(String((char*)(data.value())));
     }  
  }
  Serial.println("Peripheral disconnected");
}
  
void readValues(){
    digitalWrite(trigPin,LOW);
    delayMicroseconds(10);
    digitalWrite(trigPin,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin,LOW);
    pingTravelTime=pulseIn(echoPin,HIGH);
    pingTravelDistance=(pingTravelTime*765.*5280.*12.)/(3600.*1000000.);
    distanceToTarget=(pingTravelDistance/2)*100;
}
unsigned int getDistance() {
  readValues();
  return (unsigned int) (distanceToTarget);
}
void updateReadings() {
   unsigned int distance = getDistance();
    if (distance != previousDistance){
      Serial.print("Distance: ");
      Serial.println(distance);
      BLE_distance.writeValue(distance);
      previousDistance = distance;
    } 

}

hopefully this will make it easier to troubleshoot.

What troubles are we trying to shoot?

Does the peripheral code work correctly with a phone app like LightBlue or nrfConnect?

hi!

a quick look at your code tends to make me think you're not ready for a proper use of the BLE.

You use one arduino as central. This one is supposed to look for a specific service to connect.
You use another one as peripheral. This last one support the broadcast of the service and centrals can connect to it.

Therefore, if I see

in your cental code, there is a problem in my opinion.

Focus on the peripheral. Make it generates the BLE service

"19b10000-e8f2-537e-4f6c-d104768a1214"
and add it every characteristics you need/want.
Each one of this characteristic should be related to the peripheral activities (meaning the peripheral handle the value, don't wait for an input by the master).
Every characteristic here to be shared with the central are advertised (the peripheral tell to everyone around "hey I got some data I will please to share").

Normally, any BLE app (phone, or PC) could connect to it and see the characteristic shared. It is a good test for debugging as it don't rely on your master code (and eventually mistakes in code).

THEN, you code your master in order it launch a BLE communication and look for your specific peripheral, by the use of the service UUID.
At this point, you can play and exchange data.

Note peripheral and master are names from the BLE protocol. It is your choice for wich is wich, but the peripheral broadcast the service and the master connect to it.

May I propose you to take a look at example in BLE library? Take some time to see the difference between Master and Peripheral behaviour.

Hope you will be brave enough to go back to your code, define precisely your needs (seems ok) and apply it to the specific behavior of BLE protocol.

Maybe an example from my personnal experience: my arduino remote controlled toy car is a peripheral. It contains data to drive the motors, and data from the IMU (accelerometer, gyroscope....) as an arduino 33BLE is the core of the device.
My remote control is driven by an Arduino 33IOT and plays the master: at start up, it seeks the service provided by the car (wisely named "FOURWHEELS"), connect, then allow data exchange: position of the joystick are sent to the car and IMU's data from the car are displayed on the OLED of the remote.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.