Esp01 Wifi热点+ Web服务器不起作用

时间:2019-06-07 13:23:05

标签: arduino esp8266

我正在尝试制作一个简单的esp01 wifi热点+一个带有3个按钮的简单网页,这些按钮在按下时会通过串行方式发送ints(1,2,3)。但是wifi热点无法正常工作。

代码如下:

#include <ESP8266WiFi>;
#include <WiFiClient>;    
#include <ESP8266WebServer>;

const char *ssid = "test";
const char *password = "password";
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);

void setup() {

  delay(1000);
  Serial.begin(9600);

  WiFi.softAPConfig(local_IP, gateway, subnet);
  WiFi.softAP(ssid, password);

  server.begin();

}
void loop() {

  WiFiClient client = server.available();

  if (!client)
  {
    return;
  }

  while(!client.available())
  {
    delay(1);
  }

  String request = client.readStringUntil('\r');

  client.flush();

  if (request.indexOf("/R1") != -1)
  {
    Serial.println("1");
  }else if (request.indexOf("/R2") != -1)
  {
    Serial.println("2");
  }else if (request.indexOf("/R3") != -1)
  {
    Serial.println("3");
  }

  client.println("Content-Type: text/html");
  client.println("");
  client.println("<!DOCTYPE html>");
  client.println("<html>"); 
  client.println("<head><title>ESP01 RELAY Control</title></head>"); 
  client.println("<body>");
  client.println("<br>");
  client.println("<button href=\"/R1\">R:1</button>");
  client.println("<button href=\"/R2\">R:2</button>");
  client.println("<button href=\"/R3\">R:3</button>");    
  client.println("<br>");    
  client.println("<button href=\"/T1\">T:1</button>");    
  client.println("<button href=\"/T2\">T:2</button>");    
  client.println("<button href=\"/T3\">T:3</button>");    
  client.println("</body>");    
  client.println("</html>");

  delay(1);

}

1 个答案:

答案 0 :(得分:0)

要对ESP8622进行编程,最佳实践是使用Serial.println()命令来调试代码。要在ESP8622模块上设置工作接入点(AP),请使用以下代码;

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

const char *ssid = "test";
const char *password = "password";

IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);

WiFiServer server(80);

void setup() {
    delay(1000);
    Serial.begin(9600);

    Serial.print("Setting soft-AP configuration ... ");
    Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");

    Serial.print("Setting soft-AP ... ");
    Serial.println(WiFi.softAP(ssid, password) ? "Ready" : "Failed!");

    Serial.print("Soft-AP IP address = ");
    Serial.println(WiFi.softAPIP());

    server.begin();
}

void loop() {
    WiFiClient client = server.available();

    if(client){
        while (client.connected()) {   
            if(client.available()){
                Serial.println("Connected to client");
            }
        }
        // close the connection:
        client.stop();
    }
}