esp32 rs485
时间: 2025-01-25 11:06:17 浏览: 85
### ESP32与RS485通信教程
#### 硬件连接
为了实现ESP32通过RS485总线与其他设备进行通信,硬件连接至关重要。具体来说:
- **485转换模块的TXD** 连接到ESP32的GPIO16(用于发送)
- **485转换模块的RXD** 连接到ESP32的GPIO17(用于接收)
- **485模块的电源和地线** 需要分别连接到ESP32对应的VCC和GND端子
- **485模块的数据线A和B** 应当对应连接至目标设备上的相应接口[^1]
这种配置确保了物理层面上能够稳定传输信号。
#### 示例代码
下面是一段基于上述硬件接线方式编写的简单MicroPython程序,用来读取连接于RS485网络中的温湿度传感器数据:
```python
from machine import UART, Pin
import time
# 初始化UART串口对象
uart = UART(2, baudrate=9600, bits=8, parity=None, stop=1, tx=16, rx=17)
def send_modbus_request(slave_addr, function_code, start_register, num_registers):
request_frame = bytearray([slave_addr, function_code,
(start_register >> 8) & 0xFF, start_register & 0xFF,
(num_registers >> 8) & 0xFF, num_registers & 0xFF])
crc = calculate_crc(request_frame)
request_frame.extend(crc.to_bytes(2,'little'))
uart.write(request_frame)
def read_response():
response = uart.read()
if not response:
raise Exception('No Response from Slave Device')
# Verify CRC here before processing further...
return response
while True:
try:
send_modbus_request(1, 3, 0, 2) # 假设温度寄存器地址为0,湿度寄存器地址为1
data = read_response()
temperature = int.from_bytes(data[3:5], 'big') / 10.0
humidity = int.from_bytes(data[5:7], 'big') / 10.0
print(f'Temperature={temperature:.1f}°C Humidity={humidity:.1f}%RH')
except Exception as e:
print(e)
finally:
time.sleep_ms(2000)
```
此脚本实现了向指定从站请求两个连续寄存器值的功能,并解析返回的结果来显示当前环境条件下的温度和相对湿度信息。
阅读全文
相关推荐


















