经过实验测试ESP32单片机的网络连接还是很方便的,这里小飞鱼按照程序实例的代码亲自实验一下使用Esp32生成的网页服务来实现远程无线控制小灯开关功能,这样真的是离物联网开发越来越近了,哈哈!
连接好开发板和电路,将小灯正极连接在5号针脚上,接好负极。
程序代码:
#include <WiFi.h>
const char* ssid = "XIAOFEIYU";
const char* password = "XIAOFEIYU666";
WiFiServer server(80);
void setup()
{
Serial.begin(9600);
pinMode(5, OUTPUT); // set the LED pin mode
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
//==========================================================================
pinMode(2, OUTPUT);
digitalWrite(2, HIGH);
delay(500);
digitalWrite(2, LOW);
delay(500);
digitalWrite(2, HIGH);
delay(500);
digitalWrite(2, LOW);
delay(500);
digitalWrite(2, HIGH);
delay(2500);
digitalWrite(2, LOW);
}
void loop(){
WiFiClient client = server.available();
if (client) {
Serial.println("New Client.");
String currentLine = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n') {
if (currentLine.length() == 0) {
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("Click <a href=\"/H\">here</a> to turn the LED on pin 5 on.<br>");
client.print("Click <a href=\"/L\">here</a> to turn the LED on pin 5 off.<br>");
client.println();
break;
} else {
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
Serial.println("GET /H");
digitalWrite(5, HIGH); // GET /H 开灯
}
if (currentLine.endsWith("GET /L")) {
Serial.println("GET /L");
digitalWrite(5, LOW); // GET /L 关灯
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}
先打开串口监视器,然后编译程序上传到开发板,从串口服务器上查看到开发板的ip:192.168.199.207。
打开浏览器,输入网址可以查看到一个web页面
点击上面的一条记录上的链接,可以看到小灯被点亮了。
点击上面的一条记录上的链接,可以看到小灯熄灭了。
突然发现使用无线网络控制小灯居然可以这么神奇,各位博友有什么好的创意可以互相交流。