树莓派和ESP32S3相互通讯
时间: 2025-05-20 18:40:14 浏览: 27
### 树莓派与 ESP32-S3 的通讯方式及其实现
#### 通信方式概述
树莓派和 ESP32-S3 可以通过多种方式进行通信,常见的有 UART、I²C、SPI 和 Wi-Fi/Bluetooth 等。这些方法各有优劣,具体选择取决于应用场景和技术需求。
---
#### 1. **UART(通用异步收发传输器)**
UART 是一种简单而常用的串行通信协议,适用于低速率数据交换场景。
##### 实现步骤
- 将树莓派的 TX 引脚连接到 ESP32-S3 的 RX 引脚,反之亦然。
- 设置相同的波特率(如 9600bps 或更高)以确保双方能够正确解析数据。
##### 示例代码
以下是 Python 和 Arduino 风格 C++ 的示例代码分别运行于树莓派和 ESP32 上:
**树莓派侧 (Python):**
```python
import serial
ser = serial.Serial('/dev/ttyS0', 9600) # 替换为实际串口号
message = b'Hello from Raspberry Pi!'
ser.write(message)
response = ser.readline()
print(response.decode('utf-8'))
```
**ESP32-S3 侧 (Arduino IDE):**
```cpp
#include <HardwareSerial.h>
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
String message = Serial.readString();
Serial.println("Received: " + message); // 返回确认消息给树莓派
}
}
```
---
#### 2. **Wi-Fi / MQTT 协议**
如果需要无线通信或者远程控制,可以采用 Wi-Fi 结合 MQTT 协议实现双向交互。
##### 实现步骤
- 在 ESP32-S3 上作为客户端连接至同一局域网内的路由器。
- 树莓派充当 MQTT Broker 或者同样作为一个订阅者/发布者角色参与其中。
##### 示例代码
**树莓派侧 (MQTT Client with Paho-MQTT Library):**
```python
import paho.mqtt.client as mqtt
broker_address = "localhost"
client = mqtt.Client()
def on_message(client, userdata, msg):
print(f"Message received -> {msg.payload.decode()}")
client.on_message = on_message
client.connect(broker_address)
client.subscribe("esp32/sensor")
client.publish("raspberry/command", "Start Measurement")
client.loop_forever()
```
**ESP32-S3 侧 (PubSubClient 库):**
```cpp
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "YourSSID";
const char* password = "YourPassword";
const char* broker = "192.168.x.x"; // TreePi IP Address
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
}
void callback(char* topic, byte* payload, unsigned int length) {
String message = "";
for(int i=0;i<length;i++) message += (char)payload[i];
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("]: ");
Serial.println(message);
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32")) {
client.subscribe("raspberry/command");
} else {
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(broker, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
}
```
---
#### 3. **I²C 总线**
对于近距离且较低带宽的应用场合,可以选择 I²C 来简化硬件连线结构。
##### 实现步骤
- 把 SDA/SCL 对应针脚按照标准规范对接起来即可开始操作流程。
##### 示例代码
**树莓派侧 (Python SMBus Module):**
```python
import smbus
bus = smbus.SMBus(1) # Use '1' for newer Raspberries; older models may use '0'
address = 0x42 # Replace this address based upon your specific device configuration.
data_to_send = [0x01, 0xFF]
bus.write_i2c_block_data(address, 0, data_to_send)
received_data = bus.read_byte(address)
print(received_data)
```
**ESP32-S3 侧 (Wire Library):**
```cpp
#include <Wire.h>
#define SLAVE_ADDR 0x42
void setup() {
Wire.begin(SLAVE_ADDR);
Wire.onReceive(handleReceive);
Wire.onRequest(handleRequest);
}
void handleReceive(int howMany){
while(Wire.available()){
char c = Wire.read();
Serial.print(c);
}
}
void handleRequest(){
Wire.write("Response!");
}
void loop(){}
```
---
#### 注意事项总结
- 当使用物理线路连接时,请务必检查电压兼容性问题以防损坏任一器件[^1]。
- 如果涉及较高实时性的任务处理,则优先考虑硬实时特性较强的接口形式比如 SPI/I²C 而非软件模拟出来的选项[^2].
---
阅读全文
相关推荐


















