ESP32 BLE with RSSI Relay
Posted: Tue Jun 02, 2020 12:08 am
Hello - I'm very new to ESP32 and the Arduino IDE programming. I am looking to program my ESP32 to connect only to certain BLE addresses, once those connections are made and the RSSI reaches a certain threshold, it triggers the relay. I'm about 90% there with this sample sketch i found from a youtube video.
#include <BLEAdvertisedDevice.h>
#include <BLEDevice.h>
#include <BLEScan.h>
const int RELAY = 4;
const int CUTOFF = -80;
void setup() {
pinMode(RELAY, OUTPUT);
BLEDevice::init("Ebike");
}
void loop() {
BLEScan *scan = BLEDevice::getScan();
scan->setActiveScan(true);
BLEScanResults results = scan->start(4);
int best = CUTOFF;
for (int i = 0; i < results.getCount(); i++) {
BLEAdvertisedDevice device = results.getDevice(i);
int rssi = device.getRSSI();
if (rssi > best) {
best = rssi;
}
}
digitalWrite(RELAY, best > CUTOFF ? HIGH : LOW);
}
So far this is working well but it will trigger when any bluetooth device reaches the RSSI cutoff, how do I make it so it only connects to my iPhone's address? Also, once it connects to my device, it stops scanning, and keeps the relay on until the connection is broken. I'm using this as a "kill switch" for an electric motorcycle, so my phone will always be within the RSSI threshold while i'm riding, and i don't need it to continue scanning once i'm on the motorcycle.
Thanks for any help you can provide.
#include <BLEAdvertisedDevice.h>
#include <BLEDevice.h>
#include <BLEScan.h>
const int RELAY = 4;
const int CUTOFF = -80;
void setup() {
pinMode(RELAY, OUTPUT);
BLEDevice::init("Ebike");
}
void loop() {
BLEScan *scan = BLEDevice::getScan();
scan->setActiveScan(true);
BLEScanResults results = scan->start(4);
int best = CUTOFF;
for (int i = 0; i < results.getCount(); i++) {
BLEAdvertisedDevice device = results.getDevice(i);
int rssi = device.getRSSI();
if (rssi > best) {
best = rssi;
}
}
digitalWrite(RELAY, best > CUTOFF ? HIGH : LOW);
}
So far this is working well but it will trigger when any bluetooth device reaches the RSSI cutoff, how do I make it so it only connects to my iPhone's address? Also, once it connects to my device, it stops scanning, and keeps the relay on until the connection is broken. I'm using this as a "kill switch" for an electric motorcycle, so my phone will always be within the RSSI threshold while i'm riding, and i don't need it to continue scanning once i'm on the motorcycle.
Thanks for any help you can provide.