ESP-32 disconnects from BLE device after 5 seconds
Posted: Wed Dec 30, 2020 7:55 am
Hello!
I am trying to read data from a BLE device using an ESP-32. It works in my setup function and about 5 seconds of loop. After 5 seconds, though, it disconnects and starts displaying false values.
I have this in void setup:
This is the loop:
To connect to a client and to get a service I need these getFloraClient() and getFloraService():
And finally, here is my readFloraTemperature() function:
What is the reason of this disconnection and how could I solve it?
I am trying to read data from a BLE device using an ESP-32. It works in my setup function and about 5 seconds of loop. After 5 seconds, though, it disconnects and starts displaying false values.
I have this in void setup:
Code: Select all
char* deviceMacAddress1 = "C4:7C:8D:67:6A:23";
BLEAddress floraAddress1(deviceMacAddress1);
BLEClient* floraClient1 = getFloraClient(floraAddress1);
BLERemoteService* floraService1 = getFloraService(floraClient1);
Code: Select all
void loop() {
delay(100);
if(floraClient1->isConnected()) Serial.println("Connected to BLE");
else Serial.println("Disconnected from BLE");
Serial.println("The temperature is: ");
Serial.println(readFloraTemperature(floraService1));
}
Code: Select all
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;
}
Code: Select all
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;
}
What is the reason of this disconnection and how could I solve it?