Sunday, November 15, 2015

Standalone ESP8266/ESP-12: web control on-board LED

It's a example of Standalone ESP8266/ESP-12 web server, to control on-board LED.


Prepare:
Install ESP8266 Board to Arduino IDE
Program standalone ESP8266/ESP-12 WiFi module with Arduino IDE
Simple Web Server example of standalone ESP8266/ESP-12 WiFi Module

This example modify from the last example Simple Web Server example of standalone ESP8266/ESP-12 WiFi Module, to control on-board LED. You need a Terminal program (ex. Arduino IDE's Serial Monitor) to display the ESP8266's IP.

ESP12-WebControlLed.ino
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
 
const char* ssid = "testAP";
const char* password = "12345678";
MDNSResponder mdns;

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
  server.send(200, "text/plain", 
    "hello from esp8266!) \n/on: to tuen LED ON \n/off: to tuen LED OFF \n");

}

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", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }
  
  server.on("/", handleRoot);

  server.on("/on", [](){
    digitalWrite(BUILTIN_LED, LOW);
    server.send(200, "text/plain", "LED ON");
  });
  
  server.on("/off", [](){
    digitalWrite(BUILTIN_LED, HIGH);
    server.send(200, "text/plain", "LED OFF");
  });

  server.onNotFound(handleNotFound);
  
  server.begin();
  Serial.println("HTTP server started");

  //delay a moment, 
  //for terminal to receive inf, such as IP address
  delay(1000);
  Serial.end();
  pinMode(BUILTIN_LED, OUTPUT);
}
 
void loop(void){
  server.handleClient();
} 


Android App to test:
- Android App to control Standalone ESP8266/ESP-12 on-board LED, using HttpClient, with Android example code.


Android App to control Standalone ESP8266/ESP-12 on-board LED, using HttpURLConnection, with Android example code and APK for test without coding.


1 comment:

  1. Perfect starter project for ESP8266-12. It worked great first time. Thanks!

    ReplyDelete