Skip to content

Instantly share code, notes, and snippets.

@HectorTorres
Created May 29, 2017 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HectorTorres/2385aef487f019882ef7cfb398ec49a8 to your computer and use it in GitHub Desktop.
Save HectorTorres/2385aef487f019882ef7cfb398ec49a8 to your computer and use it in GitHub Desktop.
esp8266-web-server.c
#include "ESP8266WiFi.h";
const char* ssid = "your-ssid";
const char* password = "your-password";
// especificamos el puerto
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
// configuramos la salida (GPIO2)
pinMode(2, OUTPUT);
digitalWrite(2, 0);
// conectamos a alguna red WIFI
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");
// inciamos el servidor web
server.begin();
Serial.println("Server started");
// imprimimos la direccion IP
Serial.println(WiFi.localIP());
}
void loop() {
// revisamos si el cliente esta conectado
WiFiClient client = server.available();
if (!client) {
return;
}
// esperamos qu el cliente envie algun dato
Serial.println("new client");
while(!client.available()){
delay(1);
}
// leemos la primera linea de respuesta
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
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;
}
// configuramos la salida (GPIO2) dependiendo de la respuesta
digitalWrite(2, val);
client.flush();
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
s += (val)?"high":"low";
s += "</html>\n";
// enviamos la respuesta al cliente
client.print(s);
delay(1);
Serial.println("Client disonnected");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment