利用esp8266wifi信号强度测距

利用esp8266wifi信号强度测距_第1张图片
向esp8266发送指令

AT + CWLAP

可以得到当前可加入wifi信号的信息,其中包括的rssi,就是我们所需要的。
提取出rssi,然后带入公式

d = 10^((abs(rssi) - A) / (10 * n))

即可得到接收机和发射机之间的大概距离。
效果图
利用esp8266wifi信号强度测距_第2张图片

#include "reg52.h"
#include "string.h"
#include "math.h"

typedef unsigned int uint;
typedef unsigned char uchar;

#define NAME 9   //xutianyun
#define N 40                //N = 10 * n ,其中n为环境衰减因子,3.25-4.5
#define A 51            //接收机和发射机间隔1m时的信号强度

int rssidata = 0;
uchar recbuffer[32];
uint cnt = 0;
uint getit = 0;
uint datalen = 0;
uchar wifi_rssi[5];
uchar wifi_ssid[11] = {'"','x','u','t','i','a','n','y','u','n','"'};
float d;
uint dis;
uchar temp;

void UsartInit(void)    {
    SCON = 0x50;
    TMOD = 0x20;
    PCON = 0x80;
    TH1  = 0xF3;
    TL1  = 0xF3;
    ES   = 1;
    EA   = 1;
    TR1  = 1;
}

void SendUart(uchar value)  {
    ES = 0;
    SBUF = value;
    while(!TI);
    TI = 0;
    ES = 1;
}

void SendString(uchar *str) {
    while(*str != '\0') {
        SendUart(*str);
        str++;
    }
}

float rssiTodis(int RSSI) {
    float iu, distance;
    iu = (float)(RSSI - A) / (float)N;  
    distance = pow(10, iu);
    return distance;
}

void main() {
    UsartInit();
    while(1);
}

void Usart() interrupt 4 {
    uchar rec;
    if(RI != 0) {
        rec = SBUF;
        RI = 0;
    }
    if(rec == '"')  {
        cnt = 1;
        getit = 0;
    }
    else if(rec == ',') {
        cnt = 0;
        datalen = 0;
        if(getit == 1)  {
            SendUart(wifi_rssi[1]);
            SendUart(wifi_rssi[2]);
            SendString("\r\n");
            rssidata = (wifi_rssi[1] - '0')* 10 + (wifi_rssi[2] - '0');

            d = rssiTodis(rssidata);
            dis = d*10000;  
            temp = dis/10000 + '0';
            SendUart(temp);
            temp = dis/1000%10 + '0';
            SendUart(temp);
            temp = dis/100%10 + '0';
            SendUart(temp);
            temp = dis/10%10 + '0';
            SendUart(temp);
            temp = dis%10 + '0';
            SendUart(temp);
            SendString("\r\nok\r\n");

        }
    }
    else if(rec == '-') {
        if(strncmp(recbuffer, wifi_ssid, NAME + 2) == 0)    getit = 1;
    }

    if(cnt == 1)    {
        recbuffer[datalen++] = rec;
    }
    if(getit == 1) {
        wifi_rssi[datalen++] = rec;
    }
}

注:以上代码烧录单片机后,需要借助串口调试助手,

你可能感兴趣的:(esp8266,IoT)