Comunicação e Controle entre Dois ESPs8266 Ponto a Ponto – Peer-to-Peer – Com Roteador
Você pode se interessar também!
- Controlando LEDs com dois ESP8266 utilizando Protocolo ESP-NOW
- Como Ler Valores Analógicos ADC Usando NodeMCU ESP8266 – IDE Arduíno!
- Como Hackear Circuito Módulo Relé para funcionar com ESP8266 & ESP32 com 3.3V
- Como utilizar o Botão Flash do NodeMCU ESP8266
- Piscando LEDs Independentes sem delay() utilizando Função millis()
- Alarme de Segurança com Sensor PIR e ESP8266 – Sensor de Movimento
FUNCIONAMENTO
Par podermos dar prosseguimento a esse projeto, pré-supomos que você já tenha instalado as bibliotecas na IDE do Arduíno, se não instalou, sugerimos a você que veja nosso outro Post:
Se você já instalou, proponho prosseguirmos…
COMPONENTES NECESSÁRIOS
Os seguintes componentes são necessários para construir este projeto:
- 2 – NodeMCU (ESP8266-12E)
- 2 – Chave tipo contato – (Micro-switch, Push-button, Micro Chave, Etc…)
- 2 – LEDs
- 2 – Protoboards (Se necessário, podes utilizar fios jumpers direto)
- Fio jumpers, (macho-fêmea) para ligação das chaves e Leds
- 2 Cabos Mini-USB – (Pode utilizar só um, grava 1 ESP de cada Vez)
ESQUEMÁTICO
Os esquemas para este projeto é bastante simples, só precisaremos conectar a Micro-Switch na porta GPIO D1, e o LED na porta GPIO D0, como sugerido na Figura 2.
| Figura 2 – Diagrama Esquemático – Comunicação e Controle Ponto a Ponto |
Os Códigos
Logo abaixo temos os códigos tanto do AP – Access Point, quanto do STA – Station, ambos seguem os mesmos princípios,
AP – Access Point – “Ponto de Acesso”
Receiver_P2P_FVML
//==================================================================================//
// Adapted by: Engineer Jemerson Marques, On: 27.06.2019 - FVM Learning website //
// Available at: 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 <SPI.h>
#include <ESP8266WiFi.h> // The Basic Function Of The ESP NOD MCU
//------------------------------------------------------------------------------------
// WIFI Module Config
//------------------------------------------------------------------------------------
char ssid[] = "YourSSID"; // SSID of your home WiFi
char pass[] = "YourPassword"; // password of your home WiFi
WiFiServer server(80);
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
//------------------------------------------------------------------------------------
// Defining I/O Pins
//------------------------------------------------------------------------------------
#define LedBoard 2 // WIFI Module LED
#define LED1 D0 // LED Receiver One
#define SWITCH D1 // Button
//====================================================================================
void setup() {
Serial.begin(115200); // only for debug
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);
}
server.begin(); // starts the server
Serial.println("Connected to wifi");
Serial.print("Status: "); Serial.println(WiFi.status()); // some parameters from the network
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
Serial.print("SSID: "); Serial.println(WiFi.SSID());
Serial.print("Signal: "); Serial.println(WiFi.RSSI());
Serial.print("Networks: "); Serial.println(WiFi.scanNetworks());
pinMode(LedBoard, OUTPUT);
pinMode(LED1, OUTPUT);
pinMode(SWITCH, INPUT_PULLUP);
digitalWrite(LED1, LOW);
}
void loop() {
WiFiClient client = server.available();
if (!client) {
return;
}
digitalWrite(LedBoard, HIGH);
String request = client.readStringUntil('r');
client.flush();
if (request == "I am Transmitter") {
digitalWrite(LedBoard, LOW);
digitalWrite(LED1, !digitalRead(LED1));
Serial.print("Data Received: "); Serial.println(request);
delay(200);
digitalWrite(LedBoard, HIGH);
}
int reading = digitalRead(SWITCH);
if (reading == LOW) {
digitalWrite(LedBoard, LOW);
client.print("I am Receiverr");
delay(200);
digitalWrite(LedBoard, LOW);
}
client.println("Receiverr"); // sends the answer to the client
digitalWrite(LedBoard, HIGH);
delay(100);
}
STA – Station – “Estação” – Cliente ESP8266
Transmmiter_P2P_FVML
//==================================================================================//
// Adapted by: Engineer Jemerson Marques, On: 27.06.2019 - FVM Learning website //
// Available at: 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 <SPI.h>
#include <ESP8266WiFi.h> // The Basic Function Of The ESP NODEMCU
//------------------------------------------------------------------------------------
// Defining I/O Pins
//------------------------------------------------------------------------------------
#define LedBoard 2 // WIFI Module LED
#define LED1 D0 // LED1
#define BUTTON_1 D1 // Button 1
//------------------------------------------------------------------------------------
// WIFI Authentication Variables
//------------------------------------------------------------------------------------
char ssid[] = "YourSSID"; // SSID of your home WiFi
char pass[] = "YourPassword"; // password of your home WiFi
//------------------------------------------------------------------------------------
// WIFI Module Mode & IP
//------------------------------------------------------------------------------------
IPAddress server(192,168,25,240); // the fix IP address of the server
WiFiClient client;
//====================================================================================
void setup() {
pinMode(LedBoard, OUTPUT); // Initiate the Onboard Led Output
Serial.begin(115200); // only for debug
WiFi.begin(ssid, pass); // connects to the WiFi router
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(LedBoard, LOW);
Serial.print(".");
delay(500);
}
Serial.println("Connected to wifi");
Serial.print("Status: "); Serial.println(WiFi.status()); // Network parameters
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
Serial.print("SSID: "); Serial.println(WiFi.SSID());
Serial.print("Signal: "); Serial.println(WiFi.RSSI());
pinMode(LedBoard, OUTPUT); // Initiate the Onboard Led Output
pinMode(LED1, OUTPUT);
pinMode(BUTTON_1, INPUT_PULLUP); // Initiate the ESP Pin: INPUT_PULLUP - Its mean that you no need put resistor
digitalWrite(LED1, LOW);
}
//====================================================================================
void loop() {
ContinuousConnection();
}
//====================================================================================
void ContinuousConnection(){
client.connect(server, 80); // Connection to the server
digitalWrite(LedBoard,HIGH);
ReadButton(); // Read Button from Transmitter
}
//====================================================================================
void ReadButton() {
int reading = digitalRead(BUTTON_1);
if (reading == LOW) {
digitalWrite(LedBoard, LOW); // to show the communication only (inverted logic)
client.print("I am Transmitterr");
delay(200);
digitalWrite(LedBoard,HIGH); // to show the communication only (inverted logic)
}else{
ClientContinue();
}
}
//====================================================================================
void ClientContinue(){
client.println("Transmmiter"); // sends the message to the server
String answer = client.readStringUntil('r'); // receives the answer from the sever
client.flush();
if (answer == "I am Receiver") { // compares if the response of the receiver is equal to 'SWITCH'
digitalWrite(LED1, !digitalRead(LED1)); // if it changes the status of the LED
digitalWrite(LedBoard, LOW);
Serial.println("Data Received: " + answer);
delay(200); // client will trigger the communication 200 milliseconds
digitalWrite(LedBoard, HIGH);
}
}
//====================================================================================
ARQUIVOS PARA BAIXAR:
Você também pode baixar os arquivos (.ino) e o diagrama esquemático no link abaixo:
Link Direto: Arquivos para baixar.
Você pode também ver esse vídeo com detalhes de montagem e explanação do código em nosso canal
English
Español



