还是非常简单的,通过网页控制ESP8266,直接访问ESP8266的IP就行了。
代码:
//请先部署 ESP8266 for Arduino 环境
//随便注释了一下
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
const char* ssid = "WIFINAME";
const char* pass = "PASSWORD";
ESP8266WebServer server(80);//端口
int pin = 2;
String gethtml(){//Html
String h; //= "HTTP/1.1 200 OK\r\n";
h += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
h += "<style type=\"text/css\"> body{text-align: center;} </style>";
h += "<!DOCTYPE HTML>";
h += "<html>";
h += "<p>ESP8266</p>";
h += "<p>当前状态:";
if(digitalRead(pin) == 1){
h += "关";
}else{
h += "开";
}
h += "</p>";
h += "<a href=\"on\"><button>on</button></a>";
h += "<p> </p>";
h += "<a href=\"off\"><button>off</button></a>";
h += "<p>Powered by chutian.bid (低电平触发)</p>";
h += "</html>";
return h;
}
void onl(){
digitalWrite(pin,LOW);
Serial.println("on 0");
server.send(200, "text/html",gethtml());
}
void offl(){
digitalWrite(pin,HIGH);
Serial.println("off 1");
server.send(200, "text/html",gethtml());
}
void htmlout(){
server.send(200, "text/html",gethtml());
}
void readl(){
char* h;
if(digitalRead(pin) == 1){
h = "off";
}else{
h = "on";
}
server.send(200, "text/html",h);
}
void setup() {
Serial.begin(9600);
Serial.println();
Serial.println("ESP8266");
pinMode(pin,OUTPUT);
digitalWrite(pin, 1);//低电触发
WiFi.begin(ssid,pass);//连接WiFi
while(WiFi.status() != WL_CONNECTED){//连接判断
delay(300);
Serial.print(".");
}
Serial.println();
Serial.println(WiFi.localIP());//取IP
server.on("/on",onl);
server.on("/off",offl);
server.on("/read",readl);
server.onNotFound(htmlout);
server.begin();//开始
}
void loop() {
server.handleClient();//循环
}