树莓派与esp32无线通信

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

这个可以用,测试了一下能收到数

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值