前言
官方例程原名叫做
WiFiAccessPpoint,我改的更贴切点
代码和SimpleWiFi Server例程形似
它们所要达成的功能也是一样的
二者之间的区别是,SimpleWiFi Server是和用户处于同一wifi网络下,然后二者通信,WiFi_AP Server是esp32自己创建wifi网络,然后用户连接再通信
其他无了。。。
想了解例程运行流程的,可以看看我的SimpleWiFi Server这篇博客
代码
/*
WiFiAccessPoint.ino creates a WiFi access point and provides a web server on it.
Steps:
1. Connect to the access point "yourAp"
2. Point your web browser to http://192.168.4.1/H to turn the LED on or http://192.168.4.1/L to turn it off
OR
Run raw TCP "GET /H" and "GET /L" on PuTTY terminal with 192.168.4.1 as IP address and 80 as port
Created for arduino-esp32 on 04 July, 2018
by Elochukwu Ifediora (fedy0)
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#define LED_BUILTIN 2 // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED
// Set these to your desired credentials.
const char *ssid = "ESP32";
const char *password = "123456789";
WiFiServer server(80);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
Serial.println();
Serial.println("Configuring access point...");
// You can remove the password parameter if you want the AP to be open.
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available(); // 监听新客户端
if (client) { // 如果有客户端接入
Serial.println("New Client."); // 打印至串口
String currentLine = ""; // 用来保存客户端发来的数据
while (client.connected()) { // 当有持续连接时循环
if (client.available()) { // 如果有信息待接收
char c = client.read(); // read a byte, then
Serial.write(c); // 串口打印
if (c == '\n') { // 如果是换行符
//连续两个换行符代表,客户端http请求结束
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// esp32响应的内容
client.print("Click <a href=\"/H\">here</a> to turn ON the LED.<br>");
client.print("Click <a href=\"/L\">here</a> to turn OFF the LED.<br>");
// 以另一个换行符表示结束
client.println();
// break out of the while loop:
break;
} else { // 如果要存储新行,则先清空currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
Serial.println("_______________________开灯"); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
Serial.println("_______________________关灯"); // GET /L turns the LED off
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}
运行结果