Hi!
I am trying to read values from a Mi Flora sensor (this is a sensor that measures soil moisture, air humidity, air temperature and soil conductivity) using an ESP-32 and the BLEDevice.h library. It all seems to work fine at first, but after about 5 seconds it starts reading values that don't match the reality. For instance, the temperature that is read as 20 in the first 5 seconds becomes -358. This is my loop:
void loop() {
delay(100);
Serial.println("The temperature is: ");
Serial.println(readFloraTemperature(floraService1));
}
My readFloraTemperature function takes an BLERemoteService* as argument, so in my setup I have this:
BLEClient* floraClient1 = getFloraClient(floraAddress1);
BLERemoteService* floraService1 = getFloraService(floraClient1);
To connect to a client and to get a service I need these getFloraClient() and getFloraService():
BLEClient* getFloraClient(BLEAddress floraAddress) {
BLEClient* floraClient = BLEDevice::createClient();
if (!floraClient->connect(floraAddress)) {
Serial.println("- Connection failed, skipping");
return nullptr;
}
Serial.println("- Connection successful");
return floraClient;
}
BLERemoteService* getFloraService(BLEClient* floraClient) {
BLERemoteService* floraService = nullptr;
try {
floraService = floraClient->getService(serviceUUID);
}
catch (...) {
// something went wrong
}
if (floraService == nullptr) {
Serial.println("- Failed to find data service");
}
else {
Serial.println("- Found data service");
}
return floraService;
}
And finally, here is my readFloraTemperature() function:
int readFloraTemperature(BLERemoteService* floraService) {
BLERemoteCharacteristic* floraCharacteristic = nullptr;
// get the main device data characteristic
try {
floraCharacteristic = floraService->getCharacteristic(uuid_sensor_data);
}
catch (...) {
// something went wrong
}
if (floraCharacteristic == nullptr) {
return 200;// false;
}
// read characteristic value
std::string value;
try{
value = floraCharacteristic->readValue();
}
catch (...) {
// something went wrong
return 200;// false;
}
const char *val = value.c_str();
int16_t* temp_raw = (int16_t*)val;
float temperature = (*temp_raw) / ((float)10.0);
return temperature;
}
Till now I've tried creating the client object and connecting to it in my loop, as I thought that my ESP is disconnecting from the Flora. This change had just stopped the loop (I don't understand why it happens. It wish I will find out). What might be the problem here?
UPDATE: As I was expecting, it seems that my esp disconnects from bluetooth after 5 seconds. I have added this code in the loop:
if(floraClient1->isConnected()) Serial.println("Connected");
else Serial.println("Disconnected");
When I recieve the temperature of 20, it prints "Connected" and when it shows -358 - "Disconnected". What is the right way to connect it back without stopping the program?