项目2:蓝牙防丢器 - RSSI距离检测与手机APP报警联动
本项目将使用ESP32的蓝牙功能创建一个实用的蓝牙防丢器。当设备与手机之间的距离超过预设阈值时,手机APP会发出警报提醒用户。这个项目结合了蓝牙通信、RSSI信号强度检测和手机APP开发等多个技术点。
学习目标:掌握ESP32蓝牙功能的使用,理解RSSI信号强度与距离的关系,学会开发简单的蓝牙联动APP。
ESP32开发板
智能手机
3.7V锂电池
Arduino IDE
RSSI (Received Signal Strength Indicator) 是接收信号强度指示,可以用来估算蓝牙设备之间的距离。虽然RSSI值受环境影响较大,不能精确测量距离,但对于防丢器这样的应用已经足够。
// 获取RSSI值的示例代码
int rssi = BLEDevice::getScan()->getResults().getRSSI();
Serial.print("RSSI: ");
Serial.println(rssi);
手机APP通过蓝牙与ESP32连接,定期获取RSSI值。当RSSI值低于预设阈值(表示距离过远)时,APP会触发警报(声音、震动或通知)。
注意:RSSI值受环境影响较大,建议在实际使用前进行校准,找到适合您环境的阈值。
#include
#include
#include
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
void setup() {
Serial.begin(115200);
BLEDevice::init("ESP32_AntiLost");
BLEServer *pServer = BLEDevice::createServer();
BLEService *pService = pServer->createService(SERVICE_UUID);
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->start();
Serial.println("蓝牙广播已启动");
}
void loop() {
// 低功耗模式
esp_sleep_enable_timer_wakeup(1000000); // 1秒
esp_light_sleep_start();
}
// 蓝牙扫描回调
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
int rssi = result.getRssi();
if (rssi < THRESHOLD) {
triggerAlarm();
}
}
};
private void triggerAlarm() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (vibrator.hasVibrator()) {
vibrator.vibrate(1000); // 震动1秒
}
// 播放警报声
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.alarm);
mediaPlayer.start();
// 显示通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle("防丢器警报")
.setContentText("您的物品可能已远离!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, builder.build());
}
客服小姐姐(优先添加)
讲师微信(备用)