ESP32接TTL转485读取温湿度传感器
时间: 2025-05-15 13:01:55 浏览: 26
### 使用ESP32通过TTL转485接口读取温湿度传感器数据的方法
#### 硬件连接
为了实现ESP32与温湿度传感器之间的通信,硬件部分需按照如下方式连接:
- 将RS485转换模块的`TXD`引脚连接至ESP32的GPIO17(用于接收)
- RS485转换模块的`RXD`引脚应接到ESP32的GPIO16(负责发送)
- 同时确保给RS485模块供电正常,并将其GND接地线连回ESP32相应位置[^4]
另外,还需把RS485总线上的A端口和B端口分别对接到温湿度传感装置对应的两个差分信号输入/输出端子。
#### 软件配置及编程实例
针对软件方面,在MicroPython环境下编写代码来操作上述提到的外设资源。下面给出一段具体的Python脚本作为示范用途:
```python
from machine import UART, Pin
import time
# 初始化UART串行通信对象
uart = UART(2, baudrate=9600, tx=Pin(17), rx=Pin(16))
def read_temperature_humidity():
# 构造请求帧并发送出去查询温度湿度信息
request_frame = bytes([0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B])
uart.write(request_frame)
# 延迟等待响应到来
time.sleep_ms(100)
# 接收返回的数据包
response = uart.read()
if not response or len(response) != 8:
print('Failed to get valid data')
return None
temperature = ((response[3] << 8) | response[4]) / 10.0
humidity = ((response[5] << 8) | response[6]) / 10.0
return {'temperature': temperature, 'humidity': humidity}
while True:
result = read_temperature_humidity()
if result is not None:
print(f'Temperature: {result["temperature"]}°C, Humidity: {result["humidity"]}%')
time.sleep(5)
```
此段程序定义了一个函数`read_temperature_humidity()`用来向远程设备发出标准MODBUS RTU协议格式的消息以索取当前环境参数;之后解析收到的结果计算出实际测量值最后打印出来显示给用户查看。
阅读全文
相关推荐


















