I am trying to get my ESP32 to detect my iPhone via Bluetooth to set a GPIO pin high.
I can get this to work on my Raspberry Pi Zero W with Python fine with the below code:
Code: Select all
#!/usr/bin/python
import bluetooth
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
RELAY = 23
GPIO.setup(RELAY, GPIO.OUT)
while True:
print "Checking " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())
result = bluetooth.lookup_name('MY iPHONE MAC', timeout=5)
if (result != None):
print "User present"
GPIO.output(RELAY,1)
else:
print "User out of range"
GPIO.output(RELAY,0)
Code: Select all
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
String knownBLEAddresses[] = {"MY iPHONE MAC"};
int RSSI_THRESHOLD = -89;
bool device_found;
int scanTime = 5; //In seconds
BLEScan* pBLEScan;
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
for (int i = 0; i < (sizeof(knownBLEAddresses) / sizeof(knownBLEAddresses[0])); i++)
{
//Uncomment to Enable Debug Information
//Serial.println("*************Start**************");
//Serial.println(sizeof(knownBLEAddresses));
//Serial.println(sizeof(knownBLEAddresses[0]));
//Serial.println(sizeof(knownBLEAddresses)/sizeof(knownBLEAddresses[0]));
//Serial.println(advertisedDevice.getAddress().toString().c_str());
//Serial.println(knownBLEAddresses[i].c_str());
//Serial.println("*************End**************");
if (strcmp(advertisedDevice.getAddress().toString().c_str(), knownBLEAddresses[i].c_str()) == 0)
{
device_found = true;
break;
}
else
device_found = false;
}
Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
}
};
void setup() {
Serial.begin(115200); //Enable UART on ESP32
Serial.println("Scanning..."); // Print Scanning
pinMode(LED_BUILTIN, OUTPUT); //make BUILTIN_LED pin as output
BLEDevice::init("");
pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); //Init Callback Function
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
pBLEScan->setInterval(100); // set Scan interval
pBLEScan->setWindow(99); // less or equal setInterval value
}
void loop() {
// put your main code here, to run repeatedly:
BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
for (int i = 0; i < foundDevices.getCount(); i++)
{
BLEAdvertisedDevice device = foundDevices.getDevice(i);
int rssi = device.getRSSI();
Serial.print("RSSI: ");
Serial.println(rssi);
if (rssi > RSSI_THRESHOLD && device_found == true)
digitalWrite(LED_BUILTIN, HIGH);
else
digitalWrite(LED_BUILTIN, LOW);
}
pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory
}
Many Thanks,
Mike.