esp8266与Arduino进行通信代码
时间: 2024-05-03 20:06:52 浏览: 94
以下是ESP8266和Arduino之间进行通信的示例代码:
ESP8266端代码:
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <ESP8266WebServer.h>
ESP8266WiFiMulti wifiMulti;
WiFiServer server(80);
void setup() {
Serial.begin(115200);
wifiMulti.addAP("SSID", "PASSWORD");
while (wifiMulti.run() != WL_CONNECTED) {
delay(100);
}
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
String request = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
request += c;
}
if (request.endsWith("\r\n\r\n")) {
break;
}
delay(1);
}
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("");
client.println("<html>");
client.println("<head><title>ESP8266 to Arduino communication</title></head>");
client.println("<body>");
client.println("<h1>ESP8266 to Arduino communication</h1>");
client.println("<form method='POST' action='/'>");
client.println("<input type='text' name='data'>");
client.println("<input type='submit' value='Send'>");
client.println("</form>");
client.println("</body>");
client.println("</html>");
String data = "";
if (request.indexOf("POST / HTTP/1.1") != -1) {
data = request.substring(request.indexOf("\r\n\r\n") + 4);
}
if (data.length() > 0) {
Serial.println(data);
}
delay(1);
client.stop();
}
}
Arduino端代码:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(2, 3);
void setup() {
Serial.begin(115200);
esp8266.begin(115200);
}
void loop() {
if (esp8266.available()) {
String response = "";
while (esp8266.available()) {
char c = esp8266.read();
response += c;
}
if (response.indexOf("POST / HTTP/1.1") != -1) {
String data = response.substring(response.indexOf("\r\n\r\n") + 4);
Serial.println(data);
}
}
delay(1);
}
在此示例中,ESP8266作为Web服务器运行,Arduino通过串行连接与其通信。当Arduino接收到ESP8266发送的POST请求时,它会从请求中提取数据并将其打印到串行监视器中。您可以根据需要修改此代码以满足您的特定需求。
阅读全文