0% encontró este documento útil (0 votos)
76 vistas12 páginas

Prácticas WiFi con NodeMCU ESP8266

Este documento contiene varios ejemplos de código para conectar el módulo ESP8266 WiFi a una red inalámbrica y configurar servidores HTTP simples. Los ejemplos muestran cómo obtener y mostrar la dirección IP, encender y apagar un LED basado en solicitudes HTTP, y crear páginas web básicas para controlar el estado del LED.

Cargado por

Anthony Kiev
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
76 vistas12 páginas

Prácticas WiFi con NodeMCU ESP8266

Este documento contiene varios ejemplos de código para conectar el módulo ESP8266 WiFi a una red inalámbrica y configurar servidores HTTP simples. Los ejemplos muestran cómo obtener y mostrar la dirección IP, encender y apagar un LED basado en solicitudes HTTP, y crear páginas web básicas para controlar el estado del LED.

Cargado por

Anthony Kiev
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 12

Sistemas de Transmisión de Datos

PRACTICAS CON CONECTIVIDAD WiFI NodeMCU ESP8266


Ing. Juan Antonio CARBAJAL MAYHUA
Enlace de actualización de targeta

http://arduino.esp8266.com/stable/package_esp8266com_index.json
Ejemplo Blink 1
Ejemplo WiFi 1
Verificar el número de IP en el monitor del skecht de arduino

Ejemplo WiFi 2
Verificar el número de IP en el monitor del skecht de arduino
Ejemplo WiFi 3

EJEMPLO WiFi 4
Ejemplo WiFi 1
/*
* Juan Antonio CARBAJAL MAYHUA
* Este es un ejemplo que muestra cómo configurar un servidor simple similar al HTTP.
* El servidor configurará un pin GPIO dependiendo de la solicitud
* http: // server_ip / gpio / 0 configurará el GPIO2 bajo,
* http: // server_ip / gpio / 1 configurará el GPIO2 alto
* server_ip es la dirección IP del módulo ESP8266, será
* impreso en serie cuando el módulo está conectado.
*/
#include <ESP8266WiFi.h>
const char* ssid = "VIVOFIBRA-1344";
const char* password = "c6629c1344";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
// prepare GPIO2
pinMode(2, OUTPUT);
digitalWrite(2, 0);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
// Match the request
int val;
if (req.indexOf("/gpio/0") != -1)
val = 0;
else if (req.indexOf("/gpio/1") != -1)
val = 1;
else {
Serial.println("invalid request");
client.stop();
return;
}
// Set GPIO2 according to the request
digitalWrite(2, val);
client.flush();
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE
HTML>\r\n<html>\r\nGPIO == ";
s += (val)?"Alto":"Bajo";
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");
// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}

Ejemplo WiFi 2

#include <ESP8266WiFi.h>
const char* ssid = "VIVOFIBRA-1344";
const char* password = "c6629c1344";

int ledPin = 13; // GPIO13


WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);

// Connect to WiFi network


Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server


server.begin();
Serial.println("Server started");

// Print the IP address


Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data


Serial.println("new client");
while(!client.available()){
delay(1);
}

// Read the first line of the request


String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

// Match the request

int value = LOW;


if (request.indexOf("/LED=ON") != -1) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
value = LOW;
}

// Set ledPin according to the request


//digitalWrite(ledPin, value);

// Return the response


client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("<body>");
client.print("<h1>Hola esto es IoT - JCarbajalM</h1>");
client.print("</body>");
client.print("Salida de Led: ");

if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
client.println("<br><br>");
client.println("<a href=\"/LED=ON\"\"><button>LED On </button></a>");
client.println("<a href=\"/LED=OFF\"\"><button>LED Off </button></a><br />");
client.println("</html>");

delay(1);
Serial.println("Client disonnected");
Serial.println("");

Ejemplo WiFi 3
#include <ESP8266WiFi.h>

#include <WiFiClient.h>

#include <ESP8266WebServer.h>

#include <ESP8266mDNS.h>

const char* ssid = "WLAN_3C70"; // Enter Your wifi SSID here

const char* password = "2ySqhN24CcMa8"; // Enter Your Wifi Password Here

ESP8266WebServer server(80);

const int led = 13;


void handleRoot() {

digitalWrite(led, 1);

server.send(200, "text/plain", "Visita nuestra Web http://jcarbajalm.blogspot.pe");

digitalWrite(led, 0);

void handleNotFound(){

digitalWrite(led, 1);

String message = "File Not Found\n\n";

message += "URI: ";

message += server.uri();

message += "\nMethod: ";

message += (server.method() == HTTP_GET)?"GET":"POST";

message += "\nArguments: ";


message += server.args();

message += "\n";

for (uint8_t i=0; i<server.args(); i++){

message += " " + server.argName(i) + ": " + server.arg(i) + "\n";

server.send(404, "text/plain", message);

digitalWrite(led, 0);

void setup(void){

pinMode(led, OUTPUT);

digitalWrite(led, 0);

Serial.begin(115200);

WiFi.begin(ssid, password);

Serial.println("");

// Wait for connection


while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(".");

Serial.println("");

Serial.print("Connected to ");

Serial.println(ssid);

Serial.print("IP address: ");

Serial.println(WiFi.localIP());

if (MDNS.begin("esp8266")) {

Serial.println("MDNS responder started");

server.on("/", handleRoot);

server.on("/inline", [](){

server.send(200, "text/plain", "this works as well");

});

server.onNotFound(handleNotFound);

server.begin();

Serial.println("HTTP server started");

void loop(void){

server.handleClient();

}
Ejemplo WiFi 4
#include <ESP8266WiFi.h>

const char* ssid = "VIVOFIBRA-1344";


const char* password = "c6629c1344";

const int pin = 13; // GPIO13


WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);

pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);

// Connect to WiFi network


Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server


server.begin();
Serial.println("Server started");

// Print the IP address


Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data


Serial.println("new client");
while(!client.available()){
delay(1);
}

//Obtendo a requisicao vinda do browser


String req = client.readStringUntil('\r');
client.flush();
//Iniciando o buffer que ira conter a pagina HTML que sera enviada para o browser.
String buf = "";

buf += "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n";


buf += "<head> ";
buf += "<meta charset='UTF-8'> ";
buf += "<meta http-equiv='cache-control' content='max-age=0' /> ";
buf += "<meta http-equiv='cache-control' content='no-cache' /> ";
buf += "<meta http-equiv='expires' content='0' /> ";
buf += "<meta http-equiv='expires' content='Tue, 01 Jan 1980 1:00:00 GMT' /> ";
buf += "<meta http-equiv='pragma' content='no-cache' /> ";
buf += "<title>Juan@CARBAJAL_UNDAC</title> ";
buf += "<style> ";
buf += "body{font-family:Open Sans; color:#555555;} ";
buf += "h1{font-size:24px; font-weight:normal; margin:0.4em 0;} ";
buf += ".container { width: 100%; margin: 0 auto; } ";
buf += ".container .row { float: left; clear: both; width: 100%; } ";
buf += ".container .col { float: left; margin: 0 0 1.2em; padding-right: 1.2em; padding-left: 1.2em; } ";
buf += ".container .col.four, .container .col.twelve { width: 100%; } ";
buf += "@media screen and (min-width: 767px) { ";
buf += ".container{width: 100%; max-width: 1080px; margin: 0 auto;} ";
buf += ".container .row{width:100%; float:left; clear:both;} ";
buf += ".container .col{float: left; margin: 0 0 1em; padding-right: .5em; padding-left: .5em;} ";
buf += ".container .col.four { width: 50%; } ";
buf += ".container .col.tweleve { width: 100%; } ";
buf += "} ";
buf += "* {-moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;} ";
buf += "a{text-decoration:none;} ";
buf += ".btn {font-size: 18px; white-space:nowrap; width:100%; padding:.8em 1.5em; font-family:
Open Sans, Helvetica,Arial,sans-serif; ";
buf += "line-height:18px; display: inline-block;zoom: 1; color: #fff; text-align: center; position:relative;
";
buf += "-webkit-transition: border .25s linear, color .25s linear, background-color .25s linear; ";
buf += "transition: border .25s linear, color .25s linear, background-color .25s linear;} ";
buf += ".btn.btn-sea{background-color: #08bc9a; border-color: #08bc9a; -webkit-box-shadow: 0 3px 0
#088d74; box-shadow: 0 3px 0 #088d74;} ";
buf += ".btn.btn-sea:hover{background-color:#01a183;} ";
buf += ".btn.btn-sea:active{ top: 3px; outline: none; -webkit-box-shadow: none; box-shadow: none;} ";
buf += "</style> ";
buf += "</head> ";
buf += "<body> ";
buf += "<div class='container'> ";
buf += "<div class='row'> ";
buf += "<div class='col twelve'> ";
buf += "<p align='center'><font size='10'>Control de Encendido</font></p> ";
buf += "</div> ";
buf += "</div> ";
buf += "<div class='row'> ";
buf += "<div class='col four'> ";
buf += "<a href='?f=on' class='btn btn-sea'>LED OFF</a> ";
buf += "</div> ";
buf += "<div class='col four'> ";
buf += "<a href='?f=off' class='btn btn-sea'>LED ON</a> ";
buf += "</div> ";
buf += "</div> ";
buf += "<div class='col twelve'> ";
buf += "<p align='center'><font size='5'>Internet de las Cosas_ UNDAC</font></p> ";
buf += "</div> ";
buf += "</div> ";
buf += "</body> ";
buf += "</html> ";

//Enviando para o browser a 'pagina' criada.


client.print(buf);
client.flush();
//Analisando a requisicao recebida para decidir se liga ou desliga a lampada
if (req.indexOf("on") != -1)
{
digitalWrite(pin, LOW);
}
else if (req.indexOf("off") != -1)
{
digitalWrite(pin, HIGH);
}
else
{
//Requisicao invalida!
client.stop();
}

También podría gustarte