esp8266基本使用 - WebServer

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ZAQ1018472917/article/details/84927165

准备

手边有一块WeMos D1,上面是esp8266的wifi模块
arduino官方库提供了esp8266的Broad库,便于快速开发

安装步骤:
文件 -> 首选项 -> 附加开发板管理器网址:http://arduino.esp8266.com/stable/package_esp8266com_index.json
工具 -> 开发板 -> 开发板管理器 -> 选择安装:esp8266 by ESP8266 Community

选择对应开发板:WeMos D1


代码

该示例仅是简单使用esp8266建一个小网页,用网页控制led灯
只是为了用最简单的例子入门

1.作为终端

中文注释为比较重要的操作,关键步骤列有序号
将wemos d1作为终端,连入wifi,用其它设备接入同一wifi下进行控制

/*
    This sketch demonstrates how to set up a simple HTTP-like server.
    The server will set a GPIO pin depending on the request
      http://server_ip/gpio/0 will set the GPIO2 low,
      http://server_ip/gpio/1 will set the GPIO2 high
    server_ip is the IP address of the ESP8266 module, will be
    printed to Serial when the module is connected.
*/

#include <ESP8266WiFi.h>

const char* ssid = "##这里是自己的路由器WIFI名称##";
const char* password = "##WIFI密码##";

// 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
  // 控制片上led灯的引脚
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  // 1.设置wifi模式为终端
  WiFi.mode(WIFI_STA);
  // 2.连接wifi
  WiFi.begin(ssid, password);
//  WiFi.softAP(ssid, password);  // 开AP热点

  // 显示连接状态
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  // 3.启动服务
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  // 4.循环获取连接到此服务的客户端(就是其它设备的连接对象)
  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
  // 5.读取请求的地址数据
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();		// 清空客户端数据

  // Match the request
  // 6.在此对不同的请求地址做不同的处理(不同页面地址请求,做出不同的处理)
  int val;
  if (req.indexOf("/gpio/0") != -1) { // 硬件控制
    val = 0;
  } else if (req.indexOf("/gpio/1") != -1) {  // 硬件控制
    val = 1;
  }
  // 7.控制页面,在此显示一个UI界面页面,点击不同的按键,用一个<iframe>执行一个页面跳转激活上面的相应地址,实现页面请求,控制硬件 
  else if(req.indexOf("/") != -1){  // 控制页面
    String IPAdress = WiFi.localIP().toString();
    String html = "<html> <body>";
    html += "<script>function sendOp(value){document.getElementById('op').src = 'http://" + IPAdress + "/gpio/' + value;}</script>";
    html += "<button οnclick='sendOp(1)'>led off</button>";
    html += "<button οnclick='sendOp(0)'>led on</button>";
    html += "<iframe id='op' src='' width='0' height='0' style='border:0px' />";
    html += "</body></html>>";
    // 8.返回html页面给客户端显示
    client.print(html);
  }
  else {
    Serial.println("invalid request");
    client.stop();	// 请求完后,可以停止
    return;
  }

  // Set GPIO2 according to the request
  // 根据val值(上面不同页面请求设置),控制小灯
  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 is now ";
//  s += (val) ? "high" : "low";
//  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
}

通过其它设备,连入相同的wifi下,用浏览器访问wemos d1的的ip,即可控制控制板的片上小灯(wemos d1的ip可通过串口查看到我们输出的ip)

2.作为热点

将wemos d1作为热点,用其它设备接入连入该热点的wifi,进行控制

/*
    This sketch demonstrates how to set up a simple HTTP-like server.
    The server will set a GPIO pin depending on the request
      http://server_ip/gpio/0 will set the GPIO2 low,
      http://server_ip/gpio/1 will set the GPIO2 high
    server_ip is the IP address of the ESP8266 module, will be
    printed to Serial when the module is connected.
*/

#include <ESP8266WiFi.h>

const char* ssid = "youmux";
const char* password = "12345678";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  Serial.begin (115200);
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);
  
  // 设置内网
  IPAddress softLocal(192,168,128,1);
  IPAddress softGateway(192,168,128,1);
  IPAddress softSubnet(255,255,255,0);
  WiFi.softAPConfig(softLocal, softGateway, softSubnet);
  WiFi.softAP(ssid,password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.begin(); // 启动服务
}

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 if(req.indexOf("/") != -1){  // 控制页面
    String IPAdress = WiFi.localIP().toString();
    String html = "<html> <body>";
    html += "<script>function sendOp(value){document.getElementById('op').src = 'http://" + IPAdress + "/gpio/' + value;}</script>";
    html += "<button οnclick='sendOp(1)'>led off</button>";
    html += "<button οnclick='sendOp(0)'>led on</button>";
    html += "<iframe id='op' src='' width='0' height='0' style='border:0px' />";
    html += "</body></html>>";
    client.print(html);
  }
  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 is now ";
  s += (val) ? "high" : "low";
  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
}

通过其它设备,连入wemos开启的热点的wifi下(wifi名称:youmux wifi密码:12345678),用浏览器访问wemos d1的的ip:192.168.0.1或是192.168.1.1,即可控制控制板的片上小灯


参考:主要参考官方的例程,以及这篇文章: http://www.windworkshop.cn/?p=1215

展开阅读全文

没有更多推荐了,返回首页