Help with my Arduino nano BLE connection and MIT app inventor

Hello all, I am a ECE student trying to make an arduino project. Currently I am having trouble connecting with my device as it is stuck at connecting then disconnects after one cycle of the loop. I need help in verifying on what errors are found in my sketch.

/*
  Remote Heartrate and Temperature Monitoring
  Arduino Nano 33 BLE peripheral with a temperature and heartrate service that can be viewed
  on a mobile phone.
*/

#include <ArduinoBLE.h>
#include <Wire.h>
#include <Adafruit_MLX90614.h> //Temp Sensor
#include <Adafruit_GFX.h> // LCD Display
#include <Adafruit_SSD1306.h> // LCD Display
#include "MAX30105.h" //Heart Rate
#include "heartRate.h" //Heart Rate

MAX30105 particleSensor;

const byte RATE_SIZE = 4; //Increase this for more averaging. 4 is good.
byte rates[RATE_SIZE]; //Array of heart rates
byte rateSpot = 0;
long lastBeat = 0; //Time at which the last beat occurred

float beatsPerMinute;
int beatAvg;

#define SCREEN_WIDTH 128    // OLED display width, in pixels
#define SCREEN_HEIGHT 64    // OLED display height, in pixels
#define OLED_RESET -1       // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
 
Adafruit_MLX90614 mlx = Adafruit_MLX90614();
float temp_amb;
float temp_obj;

#define SERVICE_UUID "f97c2bec-e69e-4ddf-8e0d-b4e5d49ddf3e"
#define CHAR_UUIDtemp "7f3e5cc9-2056-4e57-8571-0ea17f8499ce"
#define CHAR_UUIDhr "935325f6-6179-4fa2-8d7f-8ac047345527"

static const char* greeting = "Health is wealth!";
BLEService customService(SERVICE_UUID);  // User defined service
BLEStringCharacteristic tempCharacteristic(CHAR_UUIDtemp, BLERead | BLENotify, 20); 
BLEStringCharacteristic hrCharacteristic(CHAR_UUIDhr, BLERead | BLENotify, 20); 

float temp;
float heartrate;

void setup() {

  Serial.begin(9600);    // initialize serial communication
  mlx.begin();         //Initialize MLX90614
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64)
  Serial.println("Temperature Sensor MLX90614");

  DisplayLCD(25, 5, 1, " Thermometer", 25, 35, 1 , "Initializing");

  delay(1000);

  // Initialize sensor
  if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) {
    Serial.println("MAX30102 was not found. Please check wiring/power. ");
    while (1);
  }
  Serial.println("Place your index finger on the sensor with steady pressure.");

  particleSensor.setup(); //Configure sensor with default settings
  particleSensor.setPulseAmplitudeRed(0x0A); //Turn Red LED to low to indicate sensor is running
  particleSensor.setPulseAmplitudeGreen(0); //Turn off Green LED

  //while (!Serial);

  pinMode(LED_BUILTIN, OUTPUT); // initialize the built-in LED pin

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

  BLE.setLocalName("Smart Bracelet");  // Set name for connection
  BLE.setAdvertisedService(customService); // Advertise service
  customService.addCharacteristic(tempCharacteristic); // Add characteristic to service
  customService.addCharacteristic(hrCharacteristic); // Add characteristic to service
  BLE.addService(customService); // Add service
  tempCharacteristic.setValue(greeting); // Set greeting string
  hrCharacteristic.setValue(greeting); // Set greeting string
  BLE.advertise();  // Start advertising

  Serial.print("Peripheral device MAC: ");
  Serial.println(BLE.address());
  Serial.println("Waiting for connections...");

}

void loop() {

  BLEDevice central = BLE.central();  // Wait for a BLE central to connect
  // if a central is connected to the peripheral:
  if (central) {
    Serial.print("Connected to central MAC: ");
    Serial.println(central.address()); // print the central's BT address:
    while (central.connected()){
      
      digitalWrite(LED_BUILTIN, HIGH); // turn on the LED to indicate the connection:
      temp = tempSensor(); //Read tempsensor data 
      heartrate = heartBPM(15000); //Read average bpm data

    // Print a message when sending notifications
    Serial.println("Sending notifications");

      //tempCharacteristic.writeValue("Temp=" + String(temp) + "C, " + "BPM=" + String(heartrate)); 
      tempCharacteristic.writeValue(String(temp));
      hrCharacteristic.writeValue(String(heartrate));
    } // keep looping while connected 

    // when the central disconnects, turn off the LED:
    digitalWrite(LED_BUILTIN, LOW);
    Serial.print("Disconnected from central MAC: ");
    Serial.println(central.address());
    DisplayLCD(5, 5, 1, "HeartTempMonitor", 25, 35, 1, "Disconnected");
    // Reinitialize BLE when disconnected
    BLE.stopAdvertise();
    BLE.begin();
    BLE.advertise();
    }   
  }

 float tempSensor(){

  //Reading room temperature and object temp
  //for reading Fahrenheit values, use
  //mlx.readAmbientTempF() , mlx.readObjectTempF() )
  temp_amb = mlx.readAmbientTempC();
  temp_obj = mlx.readObjectTempC();

  //Serial Monitor
  //Serial.print("Room Temp = ");
  //Serial.println(temp_amb);
  Serial.print("Temp = ");
  Serial.println(temp_obj);

  DisplayLCD(25, 5, 1, " Thermometer", 25, 35, 2, String(temp_obj) + String((char)247) + "C");
  return temp_obj;

  }

void DisplayLCD(int top1, int left1, int textsize1, String mesg1, int top2, int left2, int textsize2, String mesg2 ){

  display.clearDisplay();
  display.setCursor(top1,left1);  //left = 25, top = 15
  display.setTextSize(textsize1);
  display.setTextColor(WHITE);
  display.println(mesg1);
  display.setCursor(top2,left2);       //left = 25, top = 35
  display.setTextSize(textsize2);
  display.print(mesg2);
  display.display();

}

float heartBPM(int delayT){

unsigned long prMillis = millis();
Serial.print("Measuring Heart Beat");

while(millis() - prMillis < delayT)
  {
  long irValue = particleSensor.getIR();
  Serial.print(".");

  if (checkForBeat(irValue) == true) {
    //We sensed a beat!
    long delta = millis() - lastBeat;
    lastBeat = millis();

    beatsPerMinute = 60 / (delta / 1000.0);

    if (beatsPerMinute < 255 && beatsPerMinute > 20) {
      rates[rateSpot++] = (byte)beatsPerMinute; //Store this reading in the array
      rateSpot %= RATE_SIZE; //Wrap variable

      //Take average of readings
      beatAvg = 0;
      for (byte x = 0 ; x < RATE_SIZE ; x++)
        beatAvg += rates[x];
        beatAvg /= RATE_SIZE;
    }
  }

  }
  Serial.println();
  Serial.print("Avg BPM = ");
  Serial.println(beatAvg);

  DisplayLCD(25, 5, 1, "Avg BPM", 25, 35, 2, String(beatAvg) + "bpm");
  delay(1500);

  return beatAvg;
}

This is the current state of my arduino code blocks:


I havent done the other functions since I am having trouble connecting with the device.

Can you connect to the device with a phone running an app like LightBlue or nrfConnect? It will help sort out if there are issues with the Arduino BLE code or the App Inventor code.

Yes I can with nrf connect, although on my friends Xiaomi 11t pro and not on my Note 9.

If the Xiaomi 11t pro I would say the the issues are on the App Inventor side.
I'm not familiar with designing code with App Inventor, but I do believe there is an App Inventor forum, and you may want to take your issue there.

I see, but does the arduino code look sound for BLE connection?

Yes.

You can try simplify your code down to just the BLE aspects and leave out the display and sensors and see what the performance is. Just use dummy values for your Strings, and keep under 20 characters including a Null terminator.

Hello, I found this question today 03/22/2024 and I leave the solution that worked for me, I hope it is useful to you / Hola, encontré esta duda hoy 22/03/2024 y dejo la solución que a mi me sirvió, espero les sea útil

AppInventor
UI:

Code:

Arduino code
nano33_TemHumLed_Ble_DHT22.ino

/*
  Arduino Day 2024
  Taller BLE para todos
  App Arduino
  Ejemplo 3: Leer Temperatura y humedad de un Sensor DHT11
*/

// Librerias a usar
#include "bleconfig.h"
#include "temphumConfig.h"


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);  
  while(!Serial);
  pinMode(LED_BUILTIN, OUTPUT);  

  // Configurando Bluetooth LE
  if(!BLE.begin()){
    Serial.println("El servicio BLE a fallado!");
    
    while(1);
  }
  
  BLE.setLocalName("AD2024BLE");
  BLE.setAdvertisedService(temhumService);
  temhumService.addCharacteristic(temperatureLevelChar);
  temhumService.addCharacteristic(humidityLevelChar);
  BLE.addService(temhumService);
  temperatureLevelChar.writeValue(oldTemperatureLevel);
  humidityLevelChar.writeValue(oldHumidityLevel);

  BLE.advertise();
  Serial.println("Dispositivo Bluetooth activo, en espera...");

  // Configurando DHT11    
  dht.begin();
  Serial.println(F("Sensor DHT22 iniciado!"));

}

void loop() {
  // put your main code here, to run repeatedly:
  // En espera de dispositivo central
  BLEDevice central = BLE.central();
  // Leyendo Temp & Hum  
  //Serial.println(t);
  //Serial.println(h);
  // Dispositivo central se conecta
  if(central){
    Serial.println("Conectado a Central: ");
    Serial.println(central.address());
    digitalWrite(LED_BUILTIN, HIGH);

    while (central.connected()) {
      //Serial.println("ciclo while en ejecución");
      long currentMillis = millis();
      // if 200ms have passed, check the battery level:
      if (currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;
        getTempHum();
        temperatureLevelChar.writeValue(t);
        humidityLevelChar.writeValue(h);
        //Serial.println(t);
        //Serial.println(h);
      }

    }

    // Dispositivo central se desconecta
    digitalWrite(LED_BUILTIN, LOW);
    Serial.println("Desconectado de Central: ");
    Serial.println(central.address());
       

  }
}

bleconfig.h

// BLE
#include <ArduinoBLE.h>

// Configurar servicios a usar
// UUID Generator: https://www.uuidgenerator.net/version7
/*
  018e33e7-cdc5-7a09-b921-38cbbb7092c2  //Temp&Hum
  018e33e7-cdc5-7902-9a37-09404cc6a50d  //Led
*/
// Servicio Bluetooth Low Energy para Temperatura y Humedad
BLEService temhumService("018e33e7-cdc5-7a09-b921-38cbbb7092c2");

// Caracterisiticas Bluetooth Low Energy
/*
  018e33e7-cdc5-7a09-b921-38cbbb7092c3  // Temperature
  018e33e7-cdc5-7a09-b921-38cbbb7092c4  // Humidity
*/
BLEUnsignedCharCharacteristic temperatureLevelChar("018e33e7-cdc5-7a09-b921-38cbbb7092c3", BLERead | BLENotify);
BLEUnsignedCharCharacteristic humidityLevelChar("018e33e7-cdc5-7a09-b921-38cbbb7092c4", BLERead | BLENotify);

int oldTemperatureLevel = 0;
int oldHumidityLevel = 0;
long previousMillis = 0;

temhumConfig.h

// DHT11
#include "DHT.h"
#define DHTPIN 2 //20
#define DHTTYPE DHT22 //DHT11
DHT dht(DHTPIN, DHTTYPE);

int h;
int t;

void getTempHum(){
  h = dht.readHumidity();  
  t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println(F("Fallo en lectura del sensor DHT22!"));
    return;
  }
  return;
}

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