https://www.cnblogs.com/LiuXinyu12378/p/17453115.html
chatgpt
ESP32代码
#include <WiFi.h>
const char* ssid = "YourWiFiSSID";
const char* password = "YourWiFiPassword";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(1000);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Start the server
server.begin();
Serial.println("Server started");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("New client connected");
unsigned long timeout = millis() + 5000; // 5 seconds timeout
while (!client.available() && millis() < timeout) {
delay(1);
}
if (!client.available()) {
Serial.println("Client did not send data within timeout period.");
client.stop();
return;
}
// Read the first line of the request (not used, but necessary to clear the buffer)
String request = client.readStringUntil('\r');
Serial.println("Client request: " + request);
client.flush();
// Send the number to the client
int numberToSend = 123; // Change this to the number you want to send
client.println(numberToSend);
Serial.println("Number sent to client: " + String(numberToSend));
client.stop();
delay(1000); // Wait for a second before checking for new clients
}
树莓派上的Python客户端代码
确保树莓派上的客户端代码在连接后发送一些数据来触发ESP32的处理逻辑:
import socket
import time
ESP32_IP = 'ESP32的IP地址' # Replace with the actual IP address of the ESP32
ESP32_PORT = 80
while True:
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((ESP32_IP, ESP32_PORT))
# Send some data to ESP32 to trigger its processing
client_socket.sendall(b"Hello ESP32\r\n")
# Read the number from the server
response = client_socket.recv(1024).decode().strip()
if response.isdigit():
number_received = int(response)
print("Number received from ESP32:", number_received)
else:
print("Received invalid data:", response)
client_socket.close()
except Exception as e:
print(f"Failed to connect or receive data: {e}")
time.sleep(1) # Wait for 1 second before the next attempt
这个可以用,测试了一下能收到数