Comunicação entre 4 ESP8266 com central ESP com Roteador
Olá a Todos!!!
Para a realização deste procedimento, é necessário você já ter as bibliotecas do ESP instalada na IDE Arduíno.
Se você ainda não instalou. Veja o nosso Post:
Para darmos início, precisamos fazer a montagem de acordo com o esquemático na imagem ilustrativa, tanto o esquemático do CLIENT como o esquemático do SERVER.
Diagrama esquemático do Client
Todos os Clients são ligados da mesma forma, então quantos Clients você colocar, só estará limitado pelo tipo de Roteador que você tiver, pois as conexões serão feitas através do roteador, e a identificação de cada Client, é feito alterando no código o nome: Cliente 01, Cliente 02, Cliente 03 e etc.. O diagrama esquemático está disposto na Figura 2 Abaixo.
Fig. 2 - Diagrama esquemático do Client |
Diagrama Esquemático do Server
O server utiliza 5 Leds no total, 4 leds externos conectados nas GPIO D0, D2, D3, D5, e o led Onboard, na própria placa, o led na porta D0, identifica se algum cliente conectou, se houve conexão em algum cliente, ele acende e mantem-se ativado, os leds das portas D2, D3 e D5 são as portas GPIO que recebe o comando e ativa cada porta de acordo com os três clientes, o diagrama esquemático está disposto na Figura 03 logo abaixo.Fig 03 - Diagrama esquemático do Servidor |
Se você é acostumado a fazer projetos com o ESP8266, já deve ter notado que não estou utilizando resistores, porque não é necessita utilizar resistores para ligar as chaves Micro Switch, pois podemos setar as portas de entrada dos ESPs com o comando Pull_Up, e assim evitar a utilização de resistores, e nos leds também não é necessário, pois as portas dos ESPs vão de 0 à 3,3v, e a alimentação da maioria dos leds é muito próximo a isso.
Depois de montado, verifique todas as conexões, as "portas" GPIO de saída para os LEDs, verifique a polarização do LEDs, para não estar invertida, pois se tiver invertida o mesmo não irá acender, verifique as GPIOs de entrada das Micro Switch, que deve seguir como no esquemático, um lado da chave vai para a porta que você programou, no nosso caso a porta é a D0 do ESP.
Logo abaixo temos o código completo da Central, e do Cliente para você copiar. Sempre aconselhamos você baixar o arquivo .ino direto pois dependendo do navegador, ele pode modificar as pontuações e as acentuações dando erro no código, por esse motivo deixamos no link abaixo os arquivos disposto para você baixar, para você que deseja melhorar os conhecimentos, temos o vídeo no nosso canal, "Está no final da página" que explicamos o básico do código Client e do Server.
Logo abaixo temos o código completo da Central, e do Cliente para você copiar. Sempre aconselhamos você baixar o arquivo .ino direto pois dependendo do navegador, ele pode modificar as pontuações e as acentuações dando erro no código, por esse motivo deixamos no link abaixo os arquivos disposto para você baixar, para você que deseja melhorar os conhecimentos, temos o vídeo no nosso canal, "Está no final da página" que explicamos o básico do código Client e do Server.
Código Fonte do Servidor
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 75 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 96 97 98 99 90 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
//===========================================================================================//
// SERVER //
// Adapted by: Engineer Jemerson Marques, On July 29, 2019 - by Engineer Jemerson Marques //
// Communication between 4 ESPs with ESP8266 central with Router //
// The code was edited and adapted for this project. //
// Available in FVM Learning website: https://www.fvml.com.br and on //
// Youtube channel https://www.youtube.com/c/FVMLearning - I hope you have fun - Good luck //
//-------------------------------------------------------------------------------------------//
//-- Libraries Included --------------------------------------------------------------
#include <ESP8266WiFi.h>
//------------------------------------------------------------------------------------
// Define I/O Pins
#define LED0 2 // WIFI Module LED
#define LED1 D0 // Indicate Connectivity With Client "For All"
#define LED2 D2 // Connectivity With Cliente 01
#define LED3 D3 // Connectivity With Cliente 02
#define LED4 D5 // Connectivity With Cliente 03
#define MAXSC 4 // MAXIMUM NUMBER OF CLIENTS
//------------------------------------------------------------------------------------
// WIFI Module Config
//------------------------------------------------------------------------------------
char ssid[] = "FVML"; // SSID of your home WiFi
char pass[] = "fvmlearning"; // password of your home WiFi
String Message; // VARIABLE RECEIVE DATA FROM OTHER CLIENTS
WiFiServer server(80); // THE SERVER AND THE PORT NUMBER
WiFiClient Clients[MAXSC]; // THE SERVER CLIENTS (Devices)
IPAddress ip(192, 168, 25, 240); // IP address of the server
IPAddress gateway(192, 168, 25, 1); // gateway of your network
IPAddress subnet(255, 255, 255, 0); // subnet mask of your network
//====================================================================================
void setup()
{
// Setting The Serial Port
Serial.begin(115200); // Computer Communication
WiFi.config(ip, gateway, subnet); // forces to use the fix IP
WiFi.begin(ssid, pass); // connects to the WiFi router
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
} Serial.println("");
Serial.println("Server Connected");
server.begin();
// Setting The Mode Of Pins
pinMode(LED0, OUTPUT); // Setting LED0 Pin Mode Output WIFI OnBorard Led
pinMode(LED1, OUTPUT); // Setting LED1 Pin Mode Output
pinMode(LED2, OUTPUT); // Setting LED2 Pin Mode Output
pinMode(LED3, OUTPUT); // Setting LED3 Pin Mode Output
pinMode(LED4, OUTPUT); // Setting LED4 Pin Mode Output
}
//====================================================================================
void loop()
{
AvailableClients(); // Checking For Available Clients
AvailableMessage(); // Checking For Available Client Messages
}
//====================================================================================
void Availableclient()
{
if (server.hasClient())
{
// Read LED0 Switch To Low If High.
if (digitalRead(LED0) == HIGH) digitalWrite(LED0, LOW);
digitalWrite(LED1, HIGH); // Light Up LED1
for (uint8_t i = 0; i < MAXSC; i++)
{
if (!client[i] || !client[i].connected()) //find free/disconnected spot
{
if (client[i]) // Checks If Previously The Client Is Taken
{
client[i].stop();
}
if (client[i] = server.available()) // Checks If client Connected To The Server
{
Serial.println("New Client: " + String(i + 1));
}
continue; // Continue Scanning
}
}
//no free/disconnected spot so reject
WiFiClient client = server.available();
client.stop();
}
else
{
digitalWrite(LED0, HIGH); // This LED Blinks If No client Where Available
delay(250);
digitalWrite(LED0, LOW);
delay(250);
}
}
//====================================================================================
void AvailableMessage()
{
for (uint8_t i = 0; i < MAXSC; i++) //check client for data
{
if (client[i] && client[i].connected() && client[i].available())
{
while (client[i].available())
{
Message = client[i].readStringUntil('\r');
client[i].flush();
Serial.println("Client No " + String(i + 1) + " - " + Message);
ClientNumber();
}
}
}
}
// =================================================================================
void ClientNumber() {
if (Message == "<Cliente 01-1>") { // Check client number, 01 = client 1, and after trace, status 1 = on, 0 = off
digitalWrite(LED2, HIGH);
} else if (Message == "<Cliente 01-0>") {
digitalWrite(LED2, LOW);
}
if (Message == "<Cliente 02-1>") {
digitalWrite(LED3, HIGH);
} else if (Message == "<Cliente 02-0>") {
digitalWrite(LED3, LOW);
}
if (Message == "<Cliente 03-1>") {
digitalWrite(LED4, HIGH);
} else if (Message == "<Cliente 03-0>") {
digitalWrite(LED4, LOW);
}
}
//======================================== www.fvml.com.br ================================================
|
Código Fonte do Client
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 75 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 96 97 98 99 90 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
//===========================================================================================//
// CLIENT //
// Communication between 4 ESPs with ESP8266 central with Router //
// Adapted by: Engineer Jemerson Marques, On July 29, 2019 - by Engineer Jemerson Marques //
// The code was edited and adapted for this project. //
// Available in FVM Learning website: https://www.fvml.com.br and on //
// Youtube channel https://www.youtube.com/c/FVMLearning - I hope you have fun - Good luck //
//-------------------------------------------------------------------------------------------//
//------------------------------------------------------------------------------------
// Libraries Needed For This Project
//------------------------------------------------------------------------------------
#include <ESP8266WiFi.h> // The Basic Function Of The ESP NOD MCU
//------------------------------------------------------------------------------------
// Defining I/O Pins
//------------------------------------------------------------------------------------
#define LED0 2 // WIFI Module LED
#define LED1 D0 // Indicate Connectivity With Client #1
#define BUTTON D1 // Connectivity ReInitiate Button
//------------------------------------------------------------------------------------
// WIFI Authentication Variables
//------------------------------------------------------------------------------------
char ssid[] = "FVML"; // SSID of your home WiFi
char pass[] = "fvmlearning"; // password of your home WiFi
const String ClientID = "Clinete 01"; // Client Identification
//------------------------------------------------------------------------------------
// WIFI Module Mode & IP
//------------------------------------------------------------------------------------
IPAddress server(192, 168, 25, 240); // the fix IP address of the server
WiFiClient client;
//====================================================================================
void setup()
{
Serial.begin(115200); // Setting the Serial Port - Computer Communication
pinMode(LED0, OUTPUT); // Setting the Mode of Pins WIFI OnBoard LED Light
pinMode(LED1, OUTPUT); // Setting the Mode of LED1 output
pinMode(BUTTON, INPUT_PULLUP); // Setting the Mode of Pins Button as Input PullUp
digitalWrite(LED0, HIGH); // Setting WiFi LED Off
WiFi.begin(ssid, pass); // connects to the WiFi router
if (WiFi.status() == WL_CONNECTED)
{
WiFi.disconnect();
WiFi.mode(WIFI_OFF);
delay(50);
}
CheckWiFiConnectivity(); // Checking For Connection
digitalWrite(LED0, LOW); // Stop Blinking To Indicate Connected
Serial.println("Client Device Connected");
Printing IP Address --------------------------------------------------
Serial.println("Connected To : " + String(WiFi.SSID()));
Serial.println("Signal Strenght : " + String(WiFi.RSSI()) + " dBm");
Serial.print ("Server IP Address : ");
Serial.println(client);
Serial.print ("Server Port Num : ");
Serial.print ("Device MC Address : "); // Printing MAC Address
Serial.println(String(WiFi.macAddress()));
Serial.print ("Device IP Address : "); // Printing IP Address
Serial.println(WiFi.localIP());
ESPRequest(); // Conecting The Device As A Client
}
//====================================================================================
void loop()
{
ReadButton();
}
//====================================================================================
void ReadButton() // Reading Button Function
{
int reading = digitalRead(BUTTON);
if (reading == LOW)
{
int LEDState = !digitalRead(LED1);
digitalWrite(LED1, LEDState);
Serial.println ("<" + ClientID + "-" + LEDState + ">");
client.println ("<" + ClientID + "-" + LEDState + ">");
client.flush();
} delay(300);
}
//====================================================================================
void CheckWiFiConnectivity()
{
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
digitalWrite(LED0, !HIGH);
delay(250);
digitalWrite(LED0, !LOW);
delay(250);
Serial.print(".");
}
}
void ESPRequest()
{
client.stop(); // First Make Sure You Got Disconnected
if (client.connect(server, 80)); // Connection to the server
{
Serial.println ("<" + ClientID + "- CONNECTED>");
client.println ("<" + ClientID + "- CONNECTED>"); //If Sucessfully Connected Send Connection Message
client.flush();
}
}
//=================================== www.fvml.com.br ===============================================
|
ARQUIVOS PARA BAIXAR:
Você também pode baixar o arquivo .ino e o diagrama esquemático no link abaixo:
Link Direto: Arquivos para baixar
Link Direto: Arquivos para baixar
Para quem deseja ver o projeto completo, a explicação do código tanto do Client como do Server e ainda ver o funcionamento em vídeo, acesse o nosso vídeo abaixo e tenha uma boa diversão.
E por hoje é só, espero que tenham gostado!!!
E por hoje é só, espero que tenham gostado!!!
Qualquer dúvida, digita nos comentários que logos estaremos respondendo.
Se inscreva no nosso Blog!!! Click aqui - FVM Learning!!!
Forte abraço.
Deus vos Abençoe
Shalom
Opa Jemerson, o código aqui na página está com alguns erros, o nome do avaliableclient das funções tá diferente, da uma atualizada quando der, verifiquei no vídeo e tá com esse pequeno erro
ResponderExcluirOlá!
ExcluirNão consegui identificar algum erro, se puder ser mais claro, agradeçeremos!
Obrigado por estar conosco!!!
Lhes convido a se inscrever também em nosso canal no YouTube, isso nos ajuda bastante a darmos prosseguimento ao nosso trabalho, e não lhes custa nada, não é? https://www.youtube.com/channel/UCnaAKKkyhX7LY2ZYIff-qug
Forte abraço.