當手機和設備連接上後,設備端可以通過獲取RSSI來 在一定程度上判斷手機離設備的相對距離的遠近。比如藍牙防丟器就是通過RSSI來實現防丟的。
第一步:啓動rssi功能
* @param[in] conn_handle Connection handle.
* @param[in] threshold_dbm Minimum change in dBm before triggering the @ref BLE_GAP_EVT_RSSI_CHANGED event. Events are disabled if threshold_dbm equals @ref BLE_GAP_RSSI_THRESHOLD_INVALID.
* @param[in] skip_count Number of RSSI samples with a change of threshold_dbm or more before sending a new @ref BLE_GAP_EVT_RSSI_CHANGED event.
uint32_t sd_ble_gap_rssi_start(uint16_t conn_handle, uint8_t threshold_dbm, uint8_t skip_count)
傳入連接句柄、改變閾值和忽略次數。
閾值:
爲BLE_GAP_RSSI_THRESHOLD_INVALID ,忽略次數參數設置爲0,那麼每次直接調用sd_ble_gap_rssi_get 函數獲取最近一次連接事件中的RSSI值就行了。
爲0時,??????
爲5時,rssi變化值大於閾值5才產生BLE_GAP_EVT_RSSI_CHANGED事件。
忽略次數:
可以當做消抖使用。如忽略次數爲3,那麼只有rssi差值大於等於5超過 三次,第四次纔會產生BLE_GAP_EVT_RSSI_CHANGED 事件。
第二步:獲取函數:
*
@param[in] conn_handle Connection handle.
* @param[out] p_rssi Pointer to the location where the RSSI measurement shall be stored.
uint32_t sd_ble_gap_rssi_get(uint16_t conn_handle, int8_t *p_rssi)
傳入連接句柄和buff就能獲取到最近一次連接事件中的接收信號強度。
代碼來實現兩種方式:1、直接啓動,然後調用函數主動獲取。2、使用閾值和事件方式
1、直接啓動,然後調用函數主動獲取。
設置一個定時器,在設備連接上後,啓動定時器開始週期獲取RSSI.
void rssi_timeout_handler(void *p_context){
int8_t rssi;
sd_ble_gap_rssi_get(m_conn_handle, &rssi);
printf("rssi: %d\r\n",rssi);
}
2、使用閾值和事件方式
在on_ble_evt 事件處理函數中,添加當收到連接事件後rssi 測量啓動代碼,和BLE_GAP_EVT_RSSI_CHANGED事件處理代碼
代碼中我們定義rssi變化值大於5時才產生BLE_GAP_EVT_RSSI_CHANGED事件,然後在事件處理中打印rssi值
如下圖所示:
運行程序查看輸出打印可以發現 RSSI的差值都是大於等於5的