Introduction: ESP8266-201: Measuring WiFi Signal Using Socket

About: Do you like technology? Follow my channel on Youtube and my Blog. In them I put videos every week of microcontrollers, arduinos, networks, among other subjects.

In this video we will talk about ESP8266-201. I know that few people know this version, but I like it a lot because of its possibility of antenna connection. We then made an assembly to measure the signal strength of WiFi. To do this, we made the ESP201 an Access Point. We remotely communicated a second ESP8266-201 client with server and measured the signal strength between them (dbm).

So we took two ESP201s that have a PigTail connector and connected to an antenna. We made a program using Socket TCP that sends a packet and receives the power in dbm (decibel milliwatt). This is very useful, for example, when you are automating your home and do not know if the ESP used will reach the desired distance point. With today's assembly it will be possible to discover this in practice. You can still use this same example with ESP01.

The use of Socket communication will also be addressed today, which has the Station and the Client.

Step 1: Resources Used

2 ESP 8266-201;

2 Oled Displays;

2 antennas for 2.4G ESP WiFi module;

2 buttons;

2 battery holder;

4 batteries 8800mA;

Jumpers.

Step 2: ESP8266-201 Pinout

Here we have the ESP201 Pinout which is not so common but easy to find on the internet. In addition to the PigTail connector, it has more IO.

Step 3: Pin Connection

Here we have the assembly scheme, which is enough to follow, because it is very simple.

Step 4: Measured Distance

On this map, I dialed point 0 and walked straight to identify the distance reached between the two ESPs. We reached about 120 meters between the two antennas. In a first test we did last year, we reached 242 meters. However, in this new attempt we reach only 120m. The reason for this change? I do not know, but I have a theory. I think the air here where we do the tests is dirtier, with a lot of WiFi connection, which must be messing up. But of course it may be something else that I do not know since WiFi is a shaky ground. My tip here is that you use an external antenna, because it makes a lot of difference and you go much further.

The smallest signal we can identify is -96dbm. If it reaches -97dbm then communication drops. This number we identified in practice, much better than in accounts.

Step 5: Circuit

In our assembly we have the AP, which functions as the server, and the Station, which is the Client. The server sends the data to the Client, which is displayed on both displays. In both parts, the ESP201s are connected in antennas. On the back side we installed two lithium batteries in each part. The more parallel the antennas are, the better the propagation of the signal. Finally, in the Client a led flashes every packet sending to the AP.

Step 6: Access Point Code

Server Code - Includes and Settings

Here we are dealing with the server code and what does the server do? First thing: it is the AP, that is, the access. It starts as Access Point and waits for the client to connect to it. It stays in listen and when it reaches a string it goes and prints on the Oled display screen.

In this part of the code we include the libs, we create the object, we define the local IP, gate, subnet and we still create the WiFiserver, which has a Socket size number marked 5000.

#include <ESP8266WiFi.h> //lib para conectar o wifi do ESP201
#include <U8x8lib.h> //lib usada para comunicação com o display #include <SPI.h> //protocolo síncrono de dados serial //SCL (ou serial clock) indica o sinal do clock, que é enviado do servidor para todos os clientes. Todos os sinais SPI são síncronos com este sinal //SDA (ou serial data) é o pino que efetivamente transfere os dados //O 3º parameto deve ser um inteiro, ele nada mais é do que o pino do reset. 'U8X8_PIN_NONE' é usado por que este pino não está conectado U8X8_SSD1306_128X32_UNIVISION_SW_I2C u8x8(SCL, SDA, U8X8_PIN_NONE); //ip da rede local IPAddress local_IP(192, 168, 10, 11); //gateway da rede local IPAddress gateway(192, 168, 10, 10); //subnet é uma divisão lógica da rede local IPAddress subnet(255, 255, 255, 0); //define servidor na porta 5000 do protocolo TCP WiFiServer servidor(5000);

Server - Setup Code

Here we configure the LED pin, initialize the display, configure the text source and do a function to write on the display. We also configure the way Access Point is.

void setup()
{ //seta o pino do led pinMode(13, OUTPUT); //inicializa display u8x8.begin(); //desativa o modo de economia de energia do display u8x8.setPowerSave(0); //configura a fonte do texto que será exibido u8x8.setFont(u8x8_font_chroma48medium8_r); //aguarda 5 segundos delay(5000); //escreve no display "Definindo modo" escreva("Definindo modo", true, 1000, false); //configura modo como access point WiFi.mode(WIFI_AP); //escreve no display "Pronto" escreva("Pronto!", false, 1000, true);

Next, we determine that as long as the network interface of the Access Point is not configured a dot will be displayed, that is, ".". We also define what will be written in the display for other situations and the parameters of the network, such as name and password, and WiFi_Range is the name of the network that the Client will connect.

//escreve no display "Definindo AP"
escreva("Definindo AP", true, 1000, false); //enquanto a interface de rede do access point não for configurada, exibe "." while (!(WiFi.softAPConfig(local_IP, gateway, subnet))) escreva(".", false, 100, false); //escreve no display "Definindo AP" escreva("Pronto!", false, 1000, true); //escreve no display "Definindo rede" escreva("Definindo rede", true, 1000, false); //enquanto a rede não for definida, escreve "." //parametros: WiFi.softAP(nomeDoAccessPoint, senhaRede, canal, redeVisivel) //canal: canal usado pelo ESP, pode ser do 1 ao 11 //redeVisivel: a rede pode ou não aparecer para outros serviços while (!(WiFi.softAP("WiFi_Range", "12341234", 6, false))) escreva(".", false, 100, false); //escreve no display "Definindo AP" escreva("Pronto!", false, 1000, true);

In this part we deal in the IP address display, among others. We initialize the server without delay in TCP communication.

//escreve no display "Endereco IP"
escreva("Endereco IP", true, 1000, false); //escreve no display o ip do servidor escreva(WiFi.softAPIP().toString(), false, 1000, true); //escreve no display "Iniciando" escreva("Iniciando", true, 10, false); //escreve no display "servidor" escreva("servidor...", true, 1000, false); //inicializa servidor servidor.begin(); //define servidor para trabalhar sem delay //caso seja setado como true, tem o intuito de reduzir o tráfego TCP / IP de pequenos pacotes servidor.setNoDelay(true); //escreve no display "Pronto!" escreva("Pronto!", false, 1000, true); //escreve no display "Aguardando STA" escreva("Aguardando STA", true, 1000, false); }

Server - Loop Code

The code works on this part about the connection between server and client. Dropping the WiFiClient we have the object that will save all the properties of the client.

void loop()
{ //enquanto a quantidade de estações conectadas no servidor for zero //ou seja, ninguém conectou ainda while (WiFi.softAPgetStationNum() == 0) { //aguarda 1 segundo delay(1000); //se alguém conectou if (WiFi.softAPgetStationNum() != 0) { //exibe mensagem escreva("STA conectada!", true, 1000, false); } } //obtém o cliente que está conectado ao servidor WiFiClient client = servidor.available();

Next we configure assumptions with the client and define a string for displaying the signal strength of the station. We clear the arrival buffer, close the connection and turn off the led.

if (client)
{ //limpa tela do display u8x8.clear(); //acende o led digitalWrite(13, HIGH); //enquanto o cliente estiver conectado while (client.connected()) { //se houver dados, leia if (client.available()) { //recebe dados do cliente String dbmSTA = client.readStringUntil('\n'); //exibe a força do sinal da estação escreva("STA: " + dbmSTA, true, 1000, true); //espera até que todos os caracteres de saída no buffer tenham sido enviados client.flush(); } } //aguarda envio delay(1); // fecha conexão client.stop(); //apaga led digitalWrite(13, LOW); } }

Server Code - "write" function

On the "write" function, I always have the string I'm going to write on the display. In it we also deal with the range and I still have a command for cleaning the screen. That same function I use on the client as well.

//escreve no display de acordo com os parametros
//nl = pular linha //intervalo = tempo enviado para o delay //limpar = limpa a tela do display void escreva(String texto, boolean nl, int intervalo, boolean limpar) { //se deseja pular linha no display, então pula if (nl) u8x8.println(texto); else //se não, exibe texto sem pular linha u8x8.print(texto); //aguarda o intervalo passado por parametro delay(intervalo); //se deseja limpar o display, então limpa if (limpar) u8x8.clear(); }

Step 7: Customer Code (Station)

Client - Includes Code and Settings

Now on the client we have the additions of libs, display definitions and creation of an instance of class ESP8266WiFiMulti. We also created an instance of the IPAddress class and set the IP of the server.

#include <ESP8266WiFi.h> //lib para conectar o wifi do ESP201
#include <ESP8266WiFiMulti.h> //lib para as funções addAP e run #include <SPI.h> //lib usada para comunicação com o display #include //protocolo síncrono de dados serial //SCL (ou serial clock) indica o sinal do clock, que é enviado do servidor para todos os clientes. Todos os sinais SPI são síncronos com este sinal //SDA (ou serial data) é o pino que efetivamente transfere os dados //O 3º parameto deve ser um inteiro, ele nada mais é do que o pino do reset. 'U8X8_PIN_NONE' é usado por que este pino não está conectado U8X8_SSD1306_128X32_UNIVISION_SW_I2C u8x8(SCL, SDA, U8X8_PIN_NONE); //cria uma instância da classe ESP8266WiFiMulti ESP8266WiFiMulti WiFiMulti; //Criar uma instância da classe IPAddress e define o ip do servidor IPAddress local_IP(192, 168, 10, 110);

Client - Setup Code

In the Client Setup we also set the LED pin, initialize the display and set the mode to "Station".

void setup()
{ //define pino Led pinMode(pinoLed,OUTPUT); //inicializa o display u8x8.begin(); //desativa o modo de economia de energia do display u8x8.setPowerSave(0); //configura a fonte do texto que será exibido u8x8.setFont(u8x8_font_chroma48medium8_r); //aguarda 1 segundo delay(1000); //escreve no display "Definindo modo" escreva("Definindo modo", true, 1000, false); //configura modo como estação WiFi.mode(WIFI_STA); //escreve no display "Pronto!" escreva("Pronto!", false, 1000, true);

We continue to configure parameters and also define network name and password, among other commands.

//escreve no display "Definindo rede"
escreva("Definindo rede", true, 1000, false); //parametros: WiFi.softAP(nomeDoAccessPoint, senhaRede) //redeVisivel: a rede pode ou não aparecer para outros serviços WiFiMulti.addAP("WiFi_Range", "12341234"); //escreve no display "Pronto!" escreva("Pronto!", false, 1000, true); //escreve no display "Conectando" escreva("Conectando...", true, 1000, false); //enquanto o cliente não estiver conectado, escreve "." while (WiFiMulti.run() != WL_CONNECTED) escreva(".", false, 1000, false); //escreve no display "Pronto" escreva("Pronto!", false, 1000, true);

Continuing with the Setup, we define the texts to be displayed on the display according to each situation.

escreva("Endereco IP:", true, 1000, false);
//escreve no display o ip local escreva(WiFi.localIP().toString(), false, 1000, true); //escreve no display "Conectando" escreva("Conectando",true,10,false); //escreve no display "com servidor..." escreva("com servidor...",true,10,false); }

Client - Loop Code

In the Loop the size is set to 5000. The IP must be the same as the one used by the server. I define a client and connect to the "host port". If you do not do this will give error.

void loop()
{ //porta 5000 do protocolo TCP, deve ser a mesma utilizada pelo servidor const uint16_t port = 5000; //endereço ip, deve ser o mesmo utilizado pelo servidor const char * host = "192.168.10.11"; //inicializa a lib do cliente WiFiClient client; //se o cliente não estiver conectado, exibe "Falha..." if (!client.connect(host, port)) { escreva("Falha...",true, 1000,true); return; }

I get the signal strength of the connection between the ESPs and the game in the WiFi.RSSI string. We turn on the led, transmit the measurement in dBm and display the signal strength of the station on the server display.

//obtém a força do sinal da conexão entre os ESPs
String _RSSI = String(WiFi.RSSI()); //acende led digitalWrite(pinoLed,HIGH); //transmite esta medida em dBm client.println(_RSSI +"dBm"); //exibe a força do sinal da estação escreva("STA: " + _RSSI+"dBm",true,1000,true); //apaga led digitalWrite(pinoLed,LOW); }

Step 8: DBm Table

Here we have in this table how much is a unit dBm in milliwatt.