Compilation error: ISO C++ forbids comparison between pointer and integer [-fpermissive]

Hello everyone, I am trying to make a comparison between two functions pData and t1 in order to turn on an actuator (relay) but I am having this problem I know that is because I cannot combine two types of functions but I wanna know what can I change.

Thanks and Regards

Compilation error: ISO C++ forbids comparison between pointer and integer [-fpermissive]

static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {
    Serial.print("Notify callback for characteristic ");
    Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
    Serial.print(" of data length ");
    Serial.println(length);
    Serial.print("data: ");
    Serial.println((char*)pData);
    ThingSpeak.writeFields(ID,APIKey);
    Serial.println("Data sent");
     ThingSpeak.setField (1,(char*)pData); 
     char t1 = dht.readTemperature();
     ThingSpeak.setField (2,t1);  

     if ((char*)pData > t1){
       digitalWrite(rele, HIGH);
       }else{
         digitalWrite(rele, LOW);
       }
  }

Look at the extra * I put in there. It means "the object at" some pointer, not the pointer itself.
I think that should compile for you.

  • Wes
1 Like

pdata is a byte array (or perhaps a single character), and it can't be compared to an integer.

What is sending pdata, and what does the sending code look like?

1 Like

It worked but now I am having a problem with my sensor it gives me a nan value when i am trying to read its value
Temperature:

23.43?

Temperature2:
nan %

#include "ThingSpeak.h"
#include "WiFi.h"
#include "BLEDevice.h"
#include "DHT.h"

#define DHTPIN 13
#define DHTTYPE DHT11

const char* ssid = "uiw-resnet";                        //SSID de vuestro router.
const char* password = "";                //Contraseña de vuestro router.

unsigned long ID = 2050217;                //ID de vuestro canal.
const char* APIKey = "H62ZCHN3C0703GUT";     //Write API Key de vuestro canal.

WiFiClient cliente;

int rele = 12;

DHT dht(DHTPIN, DHTTYPE);

// The remote service we wish to connect to.
static BLEUUID serviceUUID("180F");
// The characteristic of the remote service we are interested in.
static BLEUUID    charUUID("2A19");

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

 
static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {
    float t1 = dht.readTemperature();
    Serial.println("Temperature: ");
    Serial.println((char*)pData);
    Serial.println(" ");
     Serial.println("Temperature2: ");
     Serial.print(t1);
     Serial.print(" %\t");
     Serial.println(" ");
    ThingSpeak.writeFields(ID,APIKey);
    ThingSpeak.setField (1,(char*)pData); 
    ThingSpeak.setField (2,t1);  

    if (*(char*)pData > t1){
       digitalWrite(rele, HIGH);
       }else{
         digitalWrite(rele, LOW);
       }


  }
  


class MyClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pclient) {
  }

  void onDisconnect(BLEClient* pclient) {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer() {
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());
    
    BLEClient*  pClient  = BLEDevice::createClient();
    Serial.println(" - Created client");

    pClient->setClientCallbacks(new MyClientCallback());

    // Connect to the remove BLE Server.
    pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
    Serial.println(" - Connected to server");

    // Obtain a reference to the service we are after in the remote BLE server.
    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
    if (pRemoteService == nullptr) {
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service");


    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
    if (pRemoteCharacteristic == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic");

    // Read the value of the characteristic.
    if(pRemoteCharacteristic->canRead()) {
      std::string value = pRemoteCharacteristic->readValue();
      Serial.print("The characteristic value was: ");
      Serial.println(value.c_str());
    }

    if(pRemoteCharacteristic->canNotify())
      pRemoteCharacteristic->registerForNotify(notifyCallback);

    connected = true;
}
/**
 * Scan for BLE servers and find the first one that advertises the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service we are looking for.
    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    } // Found our server
  } // onResult
}; // MyAdvertisedDeviceCallbacks


void setup() {
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");
  dht.begin();
//////////////////////////////////////////////////////////////////////
 WiFi.begin(ssid,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Wifi conect!");

  ThingSpeak.begin(cliente);
  
  pinMode(rele, OUTPUT);
  

  /////////////////////////////////////////////////////////////////////////////////////

  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
 //////////////////////////////////////////////////////////////////////////////////// 
} 


// This is the Arduino main loop function.
void loop() {

  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are 
  // connected we set the connected flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) {
    String newValue = "Time since boot: " + String(millis()/1000);
    Serial.println("Setting new characteristic value to \"" + newValue + "\"");
    
    // Set the characteristic's value to be the array of bytes that is actually a string.
    pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
  }else if(doScan){
    BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
  }

 
  

  

  delay(15000); // Delay a second between loops.
} // End of loop

I checked the sensor in other boards and it works fine but this one gives me that nan value what could it be maybe power or some function I am using wrong

These are my two codes the statement from weshowe worked but now I am having problems reading the values from the DHT11 it just gives me a nan as shown here:
Temperature2:
nan %
Temperature:
23.43?

my codes

#include "ThingSpeak.h"
#include "WiFi.h"
#include "BLEDevice.h"
#include "DHT.h"

#define DHTPIN 13
#define DHTTYPE DHT11

const char* ssid = "uiw-resnet";                        //SSID de vuestro router.
const char* password = "";                //Contraseña de vuestro router.

unsigned long ID = 2050217;                //ID de vuestro canal.
const char* APIKey = "H62ZCHN3C0703GUT";     //Write API Key de vuestro canal.

WiFiClient cliente;

int rele = 12;

DHT dht(DHTPIN, DHTTYPE);

// The remote service we wish to connect to.
static BLEUUID serviceUUID("180F");
// The characteristic of the remote service we are interested in.
static BLEUUID    charUUID("2A19");

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

 
static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {
    float t1 = dht.readTemperature();
    Serial.println("Temperature: ");
    Serial.println((char*)pData);
    Serial.println(" ");
     Serial.println("Temperature2: ");
     Serial.print(t1);
     Serial.print(" %\t");
     Serial.println(" ");
    ThingSpeak.writeFields(ID,APIKey);
    ThingSpeak.setField (1,(char*)pData); 
    ThingSpeak.setField (2,t1);  

    if (*(char*)pData > t1){
       digitalWrite(rele, HIGH);
       }else{
         digitalWrite(rele, LOW);
       }


  }
  


class MyClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pclient) {
  }

  void onDisconnect(BLEClient* pclient) {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer() {
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());
    
    BLEClient*  pClient  = BLEDevice::createClient();
    Serial.println(" - Created client");

    pClient->setClientCallbacks(new MyClientCallback());

    // Connect to the remove BLE Server.
    pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
    Serial.println(" - Connected to server");

    // Obtain a reference to the service we are after in the remote BLE server.
    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
    if (pRemoteService == nullptr) {
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service");


    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
    if (pRemoteCharacteristic == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic");

    // Read the value of the characteristic.
    if(pRemoteCharacteristic->canRead()) {
      std::string value = pRemoteCharacteristic->readValue();
      Serial.print("The characteristic value was: ");
      Serial.println(value.c_str());
    }

    if(pRemoteCharacteristic->canNotify())
      pRemoteCharacteristic->registerForNotify(notifyCallback);

    connected = true;
}
/**
 * Scan for BLE servers and find the first one that advertises the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service we are looking for.
    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    } // Found our server
  } // onResult
}; // MyAdvertisedDeviceCallbacks


void setup() {
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");
  dht.begin();
//////////////////////////////////////////////////////////////////////
 WiFi.begin(ssid,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Wifi conect!");

  ThingSpeak.begin(cliente);
  
  pinMode(rele, OUTPUT);
  

  /////////////////////////////////////////////////////////////////////////////////////

  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
 //////////////////////////////////////////////////////////////////////////////////// 
} 


// This is the Arduino main loop function.
void loop() {

  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are 
  // connected we set the connected flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) {
    String newValue = "Time since boot: " + String(millis()/1000);
    Serial.println("Setting new characteristic value to \"" + newValue + "\"");
    
    // Set the characteristic's value to be the array of bytes that is actually a string.
    pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
  }else if(doScan){
    BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
  }

 
  

  

  delay(15000); // Delay a second between loops.
} // End of loop

#include <ArduinoBLE.h>
#include <Arduino_HS300x.h>

BLEService temperatureService("180F");

//BLEUnsignedCharCharacteristic temperatureLevelChar("2A19",  // standard 16-bit characteristic UUID
 //   BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
BLECharacteristic temperatureLevelChar("2A19",  
    BLERead | BLENotify, 7);  //limit of "xxx.xx" + null terminator

float old_temp = 0;
float old_hum = 0; 
  
long previousMillis = 0; 
  

void setup() {
  Serial.begin(9600);    // initialize serial communication
  while (!Serial);

pinMode(LED_BUILTIN, OUTPUT);

   if (!HS300x.begin()) {
    Serial.println("Failed to initialize humidity temperature sensor!");
    while (1);
  }
  // begin initialization
  if (!BLE.begin()) {
    Serial.println("starting BLE failed!");

    while (1);
  }

  /* Set a local name for the Bluetooth® Low Energy device
     This name will appear in advertising packets
     and can be used by remote devices to identify this Bluetooth® Low Energy device
     The name can be changed but maybe be truncated based on space left in advertisement packet
  */
  BLE.setLocalName("TemperatureMonitor");
  BLE.setAdvertisedService(temperatureService); // add the service UUID
  temperatureService.addCharacteristic(temperatureLevelChar); // add the battery level characteristic
  BLE.addService(temperatureService); 
  

  /* Start advertising Bluetooth® Low Energy.  It will start continuously transmitting Bluetooth® Low Energy
     advertising packets and will be visible to remote Bluetooth® Low Energy central devices
     until it receives a new connection */

  // start advertising
  BLE.advertise();

  Serial.println("Bluetooth® device active, waiting for connections...");
}

void loop() {
  // wait for a Bluetooth® Low Energy central
  BLEDevice central = BLE.central();

  // if a central is connected to the peripheral:
  if (central) {
    Serial.print("Connected to central: ");
    // print the central's BT address:
    Serial.println(central.address());
    // turn on the LED to indicate the connection:
    digitalWrite(LED_BUILTIN, HIGH);

    
    while (central.connected()) {
     long currentMillis = millis();
    if (currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;
      
        updatetemperatureLevel();
      }
    }
    // when the central disconnects, turn off the LED:
    digitalWrite(LED_BUILTIN, LOW);
    Serial.print("Disconnected from central: ");
    Serial.println(central.address());
  }
}

void updatetemperatureLevel() {
  /* Read the current voltage level on the A0 analog input pin.
     This is used here to simulate the charge level of a battery.
  */
  float temperature = HS300x.readTemperature();
  // print each of the sensor values
  Serial.print("Temperature = ");
  Serial.print(temperature);
  Serial.println(" °C");
  static char temperatureCTemp[7]; //"xxx.xx" + null terminator
  sprintf(temperatureCTemp, "%.2f", temperature);//two places after dp
  temperatureLevelChar.writeValue(temperatureCTemp);  // and update the battery level characteristic
  old_temp = temperature;  
  delay(1000);  
}

See

maybe some points.


Meanwhile please say what you want this code to be doing:

    if (*(char*)pData > t1){
       digitalWrite(rele, HIGH);
       }else{
         digitalWrite(rele, LOW);
       }

a7

1 Like

This part will read the values from the peripheral BLE SENSE and compare it with the data from a DHT11 connected to the esp32 in such a case that the temperature from the BLE SENSE is greater than the one from the DHT11 a fan will turn on until the temperature from the BLE decrease.

The data that you read from the BLE is string, but the temperature from the sensor is integer. For example, first is "25" and second is 24. Controller can't compares the data of different types directly.
To compare the values you have to bring them to the same type. For example, use the atoi() function to convert pData to integer:

int ble_data = atoi(pData);
if ( ble_data > t1){
     digitalWrite(rele, HIGH);
     }
else{
     digitalWrite(rele, LOW);
       }
1 Like

Have you successfully read the DHT11 on the ESP32 with a simple test?

If you have done this, but can't do so in the sketch, I'm not certain that reading within the notify call back is correct.

I know there is a special DHT library tailored for the ESP32. You may want to try it.

It is available through the Library Manager. DHT ESP
https://github.com/beegee-tokyo/DHTesp

1 Like

Yes the DHT11 works fine in the ESP32 I am just having trouble with the power supply. apparently, I need an external source for both (DHT11 and ESP32) due to the power from the USB cable is not enough. I will also try this just to make sure.

Looks good but when I try it, it throws me:

Compilation error: invalid conversion from 'uint8_t* {aka unsigned char*}' to 'const char*' [-fpermissive]

You used cast in the original code. Use one in the improved code.

a7

1 Like

t1 is a float, so you should use atof() instead of atoi()

float ble_data = atof((char*)pData);

1 Like

Thank you all for your support I am sorry I could not answer earlier.

As far as now I have been able to send and read the data without a problem, using the sensor dht11 and solving the issue of the NAN value, everything works well now.

I am here again asking for help. I wanna use an if-else statement in order to compare my two temperatures values(t1 and pData) and in the case, the pData is greater than t1 led will turn on and in any other case the led will be off all the time.

We talked about using "float ble_data = atof((char*)pData);" as our final answer but now that I have already changed the code by adding a new void() I have no clue of what variable or function I can use in order to compare them but at the same time keeping the same architecture, because I spend much time figuring out how to send my two temperatures reading to Thinkspeak and serial monitor being synchronized and without any NAN or power problem.

Thanks very much for your support here is my code:

#include "ThingSpeak.h"
#include "WiFi.h"
#include "BLEDevice.h"
#include "DHT.h"

#define DHTPIN 12
#define DHTTYPE DHT11

const char* ssid = "uiw-resnet";                        //SSID de vuestro router.
const char* password = "";                //Contraseña de vuestro router.

unsigned long ID = 2050217;                //ID de vuestro canal.
const char* APIKey = "H62ZCHN3C0703GUT";     //Write API Key de vuestro canal.

WiFiClient cliente;

int rele = 19;

DHT dht(DHTPIN, DHTTYPE);

// The remote service we wish to connect to.
static BLEUUID serviceUUID("180F");
// The characteristic of the remote service we are interested in.
static BLEUUID    charUUID("2A19");

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

 
static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {

    Serial.println(" ");    
    Serial.println("Temperature: ");
    Serial.println((char*)pData);
    Serial.println(" ");
    Serial.println("Data sent");
    ThingSpeak.setField (1,(char*)pData);
  }
  
  void leer(){
float t1 = dht.readTemperature();
  Serial.println("Temperature2: ");
     Serial.print(t1);
     Serial.println(" ");
      ThingSpeak.setField (2,t1);

  }

class MyClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pclient) {
  }

  void onDisconnect(BLEClient* pclient) {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer() {
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());
    
    BLEClient*  pClient  = BLEDevice::createClient();
    Serial.println(" - Created client");

    pClient->setClientCallbacks(new MyClientCallback());

    // Connect to the remove BLE Server.
    pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
    Serial.println(" - Connected to server");

    // Obtain a reference to the service we are after in the remote BLE server.
    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
    if (pRemoteService == nullptr) {
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service");


    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
    if (pRemoteCharacteristic == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic");

    // Read the value of the characteristic.
    if(pRemoteCharacteristic->canRead()) {
      std::string value = pRemoteCharacteristic->readValue();
      Serial.print("The characteristic value was: ");
      Serial.println(value.c_str());
    }

    if(pRemoteCharacteristic->canNotify())
      pRemoteCharacteristic->registerForNotify(notifyCallback);

    connected = true;
}
/**
 * Scan for BLE servers and find the first one that advertises the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service we are looking for.
    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    } // Found our server
  } // onResult
}; // MyAdvertisedDeviceCallbacks


void setup() {
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");
  dht.begin();
//////////////////////////////////////////////////////////////////////
 WiFi.begin(ssid,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Wifi conect!");

  ThingSpeak.begin(cliente);
  
  pinMode(rele, OUTPUT);
  

  /////////////////////////////////////////////////////////////////////////////////////

  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
 //////////////////////////////////////////////////////////////////////////////////// 
} 


// This is the Arduino main loop function.
void loop() {

    leer();
     delay(1000);

  ThingSpeak.writeFields(ID,APIKey);
  Serial.println("Data sent");
  
  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are 
  // connected we set the connected flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) {
    String newValue = "Time since boot: " + String(millis()/1000);
    Serial.println("Setting new characteristic value to \"" + newValue + "\"");
    
    // Set the characteristic's value to be the array of bytes that is actually a string.
    pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
  }else if(doScan){
    BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
  }

  

  

  delay(1000); // Delay a second between loops.
} // End of loop

What have your tried?

You can write a new function compare() which takes the result of the atof
and the t1 variable from leer() and do what you want with them.

Things will be easier if both the variable assigned the result of atof() and t1 are global, and not limited to the functions where they first appear and are typed.

1 Like

I have already tried a few things and does not seem to be working. I cannot define the atof() or the t1 variable in the global because they miss a lot of characteristics that do not allow me to compile. What I've done at the end is define a new function as you said, integrating the protocol which comes with the notify callback function and adding to a new one. I redefine t1 and ble_data again and did the if-else but even when compiles it does not work.

here is the most updated code.

Note that I have added the compare(){}

Thanks for all the support

#include "ThingSpeak.h"
#include "WiFi.h"
#include "BLEDevice.h"
#include "DHT.h"

#define DHTPIN 12
#define DHTTYPE DHT11

const char* ssid = "uiw-resnet";                        //SSID de vuestro router.
const char* password = "";                //Contraseña de vuestro router.

unsigned long ID = 2050217;                //ID de vuestro canal.
const char* APIKey = "H62ZCHN3C0703GUT";   

WiFiClient cliente;

int rele = 19;

DHT dht(DHTPIN, DHTTYPE);



// The remote service we wish to connect to.
static BLEUUID serviceUUID("180F");
// The characteristic of the remote service we are interested in.
static BLEUUID    charUUID("2A19");

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

 
static void notifyCallback(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify) {

    Serial.println(" ");    
    Serial.println("Temperature: ");
    Serial.println((char*)pData);
    Serial.println(" ");
    Serial.println("Data sent");
    ThingSpeak.setField (1,(char*)pData);  
  }
  
  void read(){
  float t1 = dht.readTemperature();
  Serial.println("Temperature2: ");
  Serial.print(t1);
  Serial.println(" ");
  ThingSpeak.setField (2,t1);
  }

 void compare(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify){

float ble_data = atof((char*)pData);
float t1 = dht.readTemperature();

 if ( ble_data > t1){
     digitalWrite(rele, HIGH);
     }
else{
     digitalWrite(rele, LOW);
       }
   
 }

class MyClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pclient) {
  }

  void onDisconnect(BLEClient* pclient) {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer() {
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());
    
    BLEClient*  pClient  = BLEDevice::createClient();
    Serial.println(" - Created client");

    pClient->setClientCallbacks(new MyClientCallback());

    // Connect to the remove BLE Server.
    pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
    Serial.println(" - Connected to server");

    // Obtain a reference to the service we are after in the remote BLE server.
    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
    if (pRemoteService == nullptr) {
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service");


    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
    if (pRemoteCharacteristic == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic");

    // Read the value of the characteristic.
    if(pRemoteCharacteristic->canRead()) {
      std::string value = pRemoteCharacteristic->readValue();
      Serial.print("The characteristic value was: ");
      Serial.println(value.c_str());
    }

    if(pRemoteCharacteristic->canNotify())
      pRemoteCharacteristic->registerForNotify(notifyCallback);

    connected = true;
}
/**
 * Scan for BLE servers and find the first one that advertises the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service we are looking for.
    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    } // Found our server
  } // onResult
}; // MyAdvertisedDeviceCallbacks


void setup() {
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");
  dht.begin();
//////////////////////////////////////////////////////////////////////
 WiFi.begin(ssid,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Wifi conect!");

  ThingSpeak.begin(cliente);
  
  pinMode(rele, OUTPUT);
  

  /////////////////////////////////////////////////////////////////////////////////////

  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
 //////////////////////////////////////////////////////////////////////////////////// 
} 


// This is the Arduino main loop function.
void loop() {

    read();
     delay(1000);

  ThingSpeak.writeFields(ID,APIKey);
  Serial.println("Data sent");
  
  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are 
  // connected we set the connected flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) {
    String newValue = "Time since boot: " + String(millis()/1000);
    Serial.println("Setting new characteristic value to \"" + newValue + "\"");
    
    // Set the characteristic's value to be the array of bytes that is actually a string.
    pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
  }else if(doScan){
    BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
  }

  

  

  delay(1000); // Delay a second between loops.
} // End of loop

Try this approach

Declare two global variables for the temperatures

float t1;
float ble_data;

assign them values in the notifyCallback() and the read functions()

Use them them in compare() which becomes a function without parameters but instead uses the global variables. Call compare in loop().

#include "ThingSpeak.h"
#include "WiFi.h"
#include "BLEDevice.h"
#include "DHT.h"

#define DHTPIN 12
#define DHTTYPE DHT11

const char* ssid = "uiw-resnet";  //SSID de vuestro router.
const char* password = "";        //Contraseña de vuestro router.

unsigned long ID = 2050217;  //ID de vuestro canal.
const char* APIKey = "H62ZCHN3C0703GUT";

WiFiClient cliente;

int rele = 19;

DHT dht(DHTPIN, DHTTYPE);

float t1;
float ble_data;

// The remote service we wish to connect to.
static BLEUUID serviceUUID("180F");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("2A19");

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

static void notifyCallback(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify)
{

  Serial.println(" ");
  Serial.println("Temperature: ");
  Serial.println((char*)pData);
  Serial.println(" ");
  Serial.println("Data sent");
  ThingSpeak.setField(1, (char*)pData);
  ble_data = atof((char*)pData);
}

void read()
{
  //float t1 = dht.readTemperature();
  t1 = dht.readTemperature();
  Serial.println("Temperature2: ");
  Serial.print(t1);
  Serial.println(" ");
  ThingSpeak.setField(2, t1);
}

//void compare(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify)
void compare( )
{

  //float ble_data = atof((char*)pData);
  //float t1 = dht.readTemperature();

  if (ble_data > t1)
  {
    digitalWrite(rele, HIGH);
  }
  else
  {
    digitalWrite(rele, LOW);
  }
}

class MyClientCallback : public BLEClientCallbacks
{
  void onConnect(BLEClient* pclient)
  {
  }

  void onDisconnect(BLEClient* pclient)
  {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer()
{
  Serial.print("Forming a connection to ");
  Serial.println(myDevice->getAddress().toString().c_str());

  BLEClient* pClient = BLEDevice::createClient();
  Serial.println(" - Created client");

  pClient->setClientCallbacks(new MyClientCallback());

  // Connect to the remove BLE Server.
  pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
  Serial.println(" - Connected to server");

  // Obtain a reference to the service we are after in the remote BLE server.
  BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
  if (pRemoteService == nullptr)
  {
    Serial.print("Failed to find our service UUID: ");
    Serial.println(serviceUUID.toString().c_str());
    pClient->disconnect();
    return false;
  }
  Serial.println(" - Found our service");


  // Obtain a reference to the characteristic in the service of the remote BLE server.
  pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
  if (pRemoteCharacteristic == nullptr)
  {
    Serial.print("Failed to find our characteristic UUID: ");
    Serial.println(charUUID.toString().c_str());
    pClient->disconnect();
    return false;
  }
  Serial.println(" - Found our characteristic");

  // Read the value of the characteristic.
  if (pRemoteCharacteristic->canRead())
  {
    std::string value = pRemoteCharacteristic->readValue();
    Serial.print("The characteristic value was: ");
    Serial.println(value.c_str());
  }

  if (pRemoteCharacteristic->canNotify())
    pRemoteCharacteristic->registerForNotify(notifyCallback);

  connected = true;
}
/**
 * Scan for BLE servers and find the first one that advertises the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks
{
  /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice)
  {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service we are looking for.
    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID))
    {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    }  // Found our server
  }    // onResult
};     // MyAdvertisedDeviceCallbacks


void setup()
{
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");
  dht.begin();
  //////////////////////////////////////////////////////////////////////
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Wifi conect!");

  ThingSpeak.begin(cliente);

  pinMode(rele, OUTPUT);


  /////////////////////////////////////////////////////////////////////////////////////

  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
  ////////////////////////////////////////////////////////////////////////////////////
}


// This is the Arduino main loop function.
void loop()
{

  read();
  compare();
  delay(1000);

  ThingSpeak.writeFields(ID, APIKey);
  Serial.println("Data sent");

  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are
  // connected we set the connected flag to be true.
  if (doConnect == true)
  {
    if (connectToServer())
    {
      Serial.println("We are now connected to the BLE Server.");
    }
    else
    {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected)
  {
    String newValue = "Time since boot: " + String(millis() / 1000);
    Serial.println("Setting new characteristic value to \"" + newValue + "\"");

    // Set the characteristic's value to be the array of bytes that is actually a string.
    pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
  }
  else if (doScan)
  {
    BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
  }

  delay(1000);  // Delay a second between loops.
}  // End of loop

The program compiles but it does not work. It might be because the values from ble_data and t1 work only inside their loop. I mean the variables are declared but the values of the readings are working only inside the notifyCallback and read functions.

I also tried my previous program the one before this. I forgot to call the compare() in the loop. Now that I did it I also have this error.

Compilation error: too few arguments to function 'void compare(BLERemoteCharacteristic*, uint8_t*, size_t, bool)'

The variables are global, and should be working outside of notifyCallback and read functions.

I think you already have printouts within those two functions, but can you add some additional serial prints to loop() or the compare() function to see what the values are and if they really are not persistent.

Are you certain that the relays work correctly?

Are you using the code I posted, or did you modify some code you already were using. If so, have you made certain there are not local scope variables called t1 or ble-data?

Yes even when the variables are global the ble_data just has its attributes inside its own function:

static void notifyCallback(BLERemoteCharacteristic pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify)*

t1 is doing well on its own but ble_data gives me a 0.00 value coming from the global function. Even inside its original function, it gives me a value of 0.00

Here is the last code and its results:

#include "ThingSpeak.h"
#include "WiFi.h"
#include "BLEDevice.h"
#include "DHT.h"

#define DHTPIN 12
#define DHTTYPE DHT11

const char* ssid = "uiw-resnet";  //SSID de vuestro router.
const char* password = "";        //Contraseña de vuestro router.

unsigned long ID = 2050217;  //ID de vuestro canal.
const char* APIKey = "H62ZCHN3C0703GUT";

WiFiClient cliente;

int rele = 19;

DHT dht(DHTPIN, DHTTYPE);

float t1;
float ble_data;

// The remote service we wish to connect to.
static BLEUUID serviceUUID("180F");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("2A19");

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

static void notifyCallback(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify)
{

  Serial.println(" ");
  Serial.println("Temperature: ");
  Serial.println((char*)pData);
  Serial.println(" ");
  Serial.println("Data sent");
  ThingSpeak.setField(1, (char*)pData);
  ble_data = atof((char*)pData);
}

void read()
{
  t1 = dht.readTemperature();
  Serial.println("Temperature2: ");
  Serial.print(t1);
  Serial.println(" ");
  ThingSpeak.setField(2, t1);
}


void compare()
{
 
 Serial.print("Test t1");
 Serial.print(t1);
 Serial.println(" ");
 Serial.print("Test ble_data");
 Serial.print(ble_data);

  if (ble_data > t1)
  {
    digitalWrite(rele, HIGH);
  }
  else
  {
    digitalWrite(rele, LOW);
  }
}

class MyClientCallback : public BLEClientCallbacks
{
  void onConnect(BLEClient* pclient)
  {
  }

  void onDisconnect(BLEClient* pclient)
  {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer()
{
  Serial.print("Forming a connection to ");
  Serial.println(myDevice->getAddress().toString().c_str());

  BLEClient* pClient = BLEDevice::createClient();
  Serial.println(" - Created client");

  pClient->setClientCallbacks(new MyClientCallback());

  // Connect to the remove BLE Server.
  pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
  Serial.println(" - Connected to server");

  // Obtain a reference to the service we are after in the remote BLE server.
  BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
  if (pRemoteService == nullptr)
  {
    Serial.print("Failed to find our service UUID: ");
    Serial.println(serviceUUID.toString().c_str());
    pClient->disconnect();
    return false;
  }
  Serial.println(" - Found our service");


  // Obtain a reference to the characteristic in the service of the remote BLE server.
  pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
  if (pRemoteCharacteristic == nullptr)
  {
    Serial.print("Failed to find our characteristic UUID: ");
    Serial.println(charUUID.toString().c_str());
    pClient->disconnect();
    return false;
  }
  Serial.println(" - Found our characteristic");

  // Read the value of the characteristic.
  if (pRemoteCharacteristic->canRead())
  {
    std::string value = pRemoteCharacteristic->readValue();
    Serial.print("The characteristic value was: ");
    Serial.println(value.c_str());
  }

  if (pRemoteCharacteristic->canNotify())
    pRemoteCharacteristic->registerForNotify(notifyCallback);

  connected = true;
}
/**
 * Scan for BLE servers and find the first one that advertises the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks
{
  /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice)
  {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service we are looking for.
    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID))
    {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    }  // Found our server
  }    // onResult
};     // MyAdvertisedDeviceCallbacks


void setup()
{
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");
  dht.begin();
  //////////////////////////////////////////////////////////////////////
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Wifi conect!");

  ThingSpeak.begin(cliente);

  pinMode(rele, OUTPUT);


  /////////////////////////////////////////////////////////////////////////////////////

  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
  ////////////////////////////////////////////////////////////////////////////////////
}


// This is the Arduino main loop function.
void loop()
{

  read();
  compare();
  delay(1000);

  ThingSpeak.writeFields(ID, APIKey);
  Serial.println("Data sent");

  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are
  // connected we set the connected flag to be true.
  if (doConnect == true)
  {
    if (connectToServer())
    {
      Serial.println("We are now connected to the BLE Server.");
    }
    else
    {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected)
  {
    String newValue = "Time since boot: " + String(millis() / 1000);
    Serial.println("Setting new characteristic value to \"" + newValue + "\"");

    // Set the characteristic's value to be the array of bytes that is actually a string.
    pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
  }
  else if (doScan)
  {
    BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
  }

  delay(1000);  // Delay a second between loops.
}  // End of loop

The results are listed as:
Temperature 0.00
Temperature2 21.24
Test t1 21.24
Test ble_data 0.00