Skip to content

Instantly share code, notes, and snippets.

@youjunjer
Last active August 12, 2020 17:25
Show Gist options
  • Save youjunjer/e73575aaad1236bf19b0f500043c7cde to your computer and use it in GitHub Desktop.
Save youjunjer/e73575aaad1236bf19b0f500043c7cde to your computer and use it in GitHub Desktop.
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEUUID.h>
#include <BLEAdvertisedDevice.h>
#include <BLEBeacon.h>
BLEScan* pBLEScan;
BLEBeacon id;
int scanTime = 3; //In seconds
String reverse(String str) {
String rev;
for (int i = str.length() - 1; i >= 0; i--) {
rev = rev + str[i];
}
return rev;
}
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks
{
void onResult(BLEAdvertisedDevice advertisedDevice)
{
id.setData(advertisedDevice.getManufacturerData());
//Print UUID
Serial.print("UUID :");
String bUUID = id.getProximityUUID().toString().c_str();
bUUID = reverse(bUUID);
Serial.print(bUUID);
//Print RSSI
Serial.print(",RSSI :");
int bRSSI = advertisedDevice.getRSSI();
Serial.print(bRSSI);
//Print Major
Serial.print(",Major :");
int bMajor = id.getMajor() / 256;
Serial.print(bMajor);
//Print Minor
Serial.print(",Minor :");
int bMinor = id.getMinor() / 256;
Serial.print(bMinor);
Serial.println("");
//如果找到的UUID相同,且RSSI大於-50時,亮燈
if ( bUUID == "00999999-9999-5555-5555-551111111111" && bRSSI >= -50) {
digitalWrite(2, HIGH);
} else {
digitalWrite(2, LOW);
}
}
};
void setup() {
Serial.begin(115200);
BLEDevice::init("");
pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
Serial.println("Scanning...");
pinMode(2, OUTPUT);
}
void loop()
{
BLEScanResults foundDevices = pBLEScan->start(scanTime);
Serial.print("Devices found: ");
Serial.println(foundDevices.getCount());
Serial.println("Scan done!");
pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment