写一个ESP8266串口发-WIFI接,WIFI发-串口接的代码
时间: 2024-12-10 14:08:53 浏览: 19
ESP8266是一款常用的物联网Wi-Fi模块,它支持WiFi通信和串口通信功能。下面是一个简单的示例,展示了如何在ESP8266上实现串口到WiFi的发送数据以及WiFi到串口的接收数据的基本流程。这个例子使用的是NodeMCU库,适用于Arduino环境。
```cpp
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const int txPin = D0; // ESP8266 RX pin connected to Arduino TX pin
const int rxPin = D1; // ESP8266 TX pin connected to Arduino RX pin
ESP8266WebServer server(80); // Create a web server on port 80
ESP8266HTTPClient client;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
server.on("/", handleRoot);
server.begin();
}
void loop() {
if (!client.connect("your_server_url.com", 80)) { // Replace with your server address
Serial.println("Connection failed");
} else {
String message = readSerialLine(txPin); // Read from serial line
client.print("POST /send HTTP/1.1\r\n");
client.print("Content-Type: text/plain\r\n");
client.print("Content-Length: ");
client.print(message.length());
client.println("\r\n");
client.print(message + "\r\n\r\n");
client.stop(); // Close connection after sending data
}
server.handleClient(); // Handle incoming HTTP requests
}
String readSerialLine(int pin) {
String line;
while (Serial.available()) {
char c = Serial.read();
if (c == '\n') break;
line += c;
}
return line.trim();
}
// Handle the root page request
void handleRoot() {
if (client.header("GET") == "/send") { // Check if requesting the send form
String message = readSerialLine(txPin);
if (!message.isEmpty()) {
client.println("200 OK");
client.println("Content-Type: text/html");
client.println("<!DOCTYPE html>");
client.println("<html><body>");
client.println("<h1>Message Sent:</h1>");
client.println("<p>" + message + "</p>");
client.println("</body></html>");
} else {
client.println("400 Bad Request");
}
}
}
```
**注意事项:**
1. 将`your_SSID`, `your_PASSWORD`, 和 `your_server_url.com`替换为实际的SSID、密码和服务器地址。
2. 确保ESP8266的TX和RX引脚连接到Arduino的相应位置。
阅读全文