两个esp8266之间进行wifi通讯,一个做主站另一个从站,传递int型数据,分别输出主站和从站代码
时间: 2023-05-29 14:02:04 浏览: 145
ESP8266 链接WiFi
4星 · 用户满意度95%
以下是两个esp8266之间进行wifi通讯,一个做主站另一个从站,传递int型数据的代码。
主站代码:
```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* host = "192.168.1.2"; // 从站的IP地址
WiFiClient client;
void setup(){
Serial.begin(115200);
delay(10);
//连接WiFi
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());
}
int counter = 0;
void loop(){
delay(1000);
//连接从站
if (!client.connect(host, 80)) {
Serial.println("connection failed");
return;
}
//发送数据
counter++;
String message = String(counter);
Serial.print("Sending message: ");
Serial.println(message);
client.print(message);
//等待数据回复
while(client.available()) {
char c = client.read();
Serial.write(c);
}
//断开连接
client.stop();
}
```
从站代码:
```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
//连接WiFi
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();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("New client");
while (client.connected()) {
if (client.available()) {
int data = client.parseInt(); //读取数据
Serial.println(data); //输出数据
client.print("Data received successfully"); //回复数据
}
}
client.stop();
Serial.println("Client disconnected");
}
}
```
阅读全文