ESP32的基本功能就是它的WIFI无线功能,现在我们就基于该功能实现远程控制零知ESP32板载LED灯的打开和关闭操作。
硬件我们本次使用零知-ESP32;
/*
* This sketch sends a message to a TCP server
*
*/
#include <WiFi.h>
#include <WiFiMulti.h>
WiFiMulti WiFiMulti;
void setup()
{
Serial.begin(115200);
delay(10);
pinMode(LED_BUILTIN,OUTPUT);
// We start by connecting to a WiFi network
WiFiMulti.addAP("xx", "xx");
Serial.println();
Serial.println();
Serial.print("Waiting for WiFi... ");
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
void loop()
{
const uint16_t port = 8888;
const char * host = "192.168.0.116"; // ip or dns
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection failed.");
Serial.println("Waiting 5 seconds before retrying...");
delay(5000);
return;
}
// This will send a request to the server
client.print("Send this data to the server");
//read back one line from the server
while(1){
String line = client.readStringUntil('\r');
if(line == ""){
continue;
}
Serial.print(line);
if(line == "on"){
digitalWrite(LED_BUILTIN,HIGH);
}else if(line == "off"){
digitalWrite(LED_BUILTIN,LOW);
}else{
Serial.println("unknown cmd:"+line);
}
}
// String line = client.readStringUntil('\r');
// client.println(line);
Serial.println("Closing connection.");
client.stop();
Serial.println("Waiting 5 seconds before restarting...");
delay(5000);
}
这里其实使用TCP协议进行数据传输,这里需要再代码中填写自己的WIFI热点名称和密码。
(1)首先,我们需要在手机端开启TCP服务器,然后在代码中填写我们开启的服务端IP。在这里使用网络调试助手:网络调试助手.7z(点击下载)
(2)开启TCP服务器,并设置端口号8888,这里与代码中是一致的:
(3)然后打开串口调试窗口,可以看到如下信息:
我们在手机端发送“on”和“off”,可以看到板载LED就可以控制了。