Arduino+ESP8266wifi+html实现控制小灯

Arduino+ESP8266wifi+html实现控制小灯

esp8266wifi灯控连线

继电器in口接D4口

串口打印(选择正确的波特率,我的第一行就是教训)

Arduino+ESP8266wifi+html实现控制小灯_第1张图片

连接wifi,访问网页实现操作

Arduino+ESP8266wifi+html实现控制小灯_第2张图片

代码

Arduino IDE代码 (为了方便我直接基于helloserver进行了修改)

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "wifi名称";               
const char* password = "wifi密码";
//压缩后的html代码
String html = "                    ";

//主要添加了这个函数
void pin(){
  if(server.arg("light")=="on"{
  digitalWrite(D4, LOW);         //低电平有效
  server.send(200, "text/html",html);
  }else if(server.arg("light"=="off"){
    digitalWrite(D4, HIGH);     //di'dian'ping
  server.send(200, "text/html",html);
  }
  }
  
ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/html",html);
  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(D4, OUTPUT);  //初始化D4引脚
  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("/pin", HTTP_GET, pin);

  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();
}

html代码(压缩时需要在双引号前加“\”,或者用单引号替换)



	
		
		ControlPage
	
	
		
		
	

你可能感兴趣的:(ESP8266)