本帖主要讲解ESP8266 WIFI功能关于TCP协议网络传输的应用,这里演示了ESP8266作为TCP服务器的一个示例: 1、硬件 零知ESP8266开发板 2、软件 (1)代码如下: - /**********************************************************
- * 文件: tcp-server.ino by 零知实验室
- * -^^- 零知开源,让电子制作变得更简单! -^^-
- * 时间: 2019/06/17 14:12
- * 说明:
- ************************************************************/
- #include <ESP8266WiFi.h>
-
- int port = 8888; //Port number
- WiFiServer server(port);
-
- //Server connect to WiFi Network
- const char *ssid = "xx"; //Enter your wifi SSID
- const char *password = "xx"; //Enter your wifi Password
-
- int count=0;
-
- // 复位或上电后运行一次:
- void setup() {
- //在这里加入初始化相关代码,只运行一次:
- Serial.begin(115200);
-
- Serial.println();
-
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password); //Connect to wifi
-
- // Wait for connection
- Serial.println("Connecting to Wifi");
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- delay(500);
- }
-
- Serial.println("");
- Serial.print("Connected to ");
- Serial.println(ssid);
-
- Serial.print("IP address: ");
- Serial.println(WiFi.localIP());
- Serial.print("port:");
- Serial.println(port);
- server.begin();
- }
-
- //一直循环执行:
- void loop() {
- // 在这里加入主要程序代码,重复执行:
- WiFiClient client = server.available();
-
- if (client) {
- if(client.connected())
- {
- Serial.println("Client Connected");
- }
-
- while(client.connected()){
- while(client.available()>0){
- // read data from the connected client
- Serial.write(client.read());
- }
- //Send Data to connected client
- while(Serial.available()>0)
- {
- client.write(Serial.read());
- }
- }
- client.stop();
- Serial.println("Client disconnected");
- }
- }
复制代码 3、验证测试
(1)将上面代码验证后并上传到零知ESP8266,然后打开串口调试窗口,可以看到如下信息:
现在已经将ESP8266作为TCP服务器了,上面信息为IP和端口
(2)打开零知工具箱的网络调试窗口,然后选择TCP客户端,并填写上面的IP和端口:
PS:零知工具箱请至零知官网“软件下载”页面获取
(3)点击【连接】后,就与ESP8266建立的TCP连接了,就可以发送和接收数据了,如下:
|