香橙派/树莓派读取GY39数据
目录
前言
环境安装
效果
代码:
前言
网上还没啥GY39树莓派的代码
这次使用的是串口通信
悬空S0引脚
接上串口使用的4个引脚就可以了
环境安装
pip3 install pyserial
香橙派配置串口:
sudo orangepi-config
配置后重启就行:
效果:

代码:
import serial
import timeSERIAL_PORT = "/dev/ttyS0" # 根据实际情况修改
BAUDRATE = 9600def read_environment():try:with serial.Serial(SERIAL_PORT, BAUDRATE, timeout=1) as ser:# 发送查询环境数据的指令ser.write(bytes([0xA5, 0x52, 0xF7]))time.sleep(0.1) # 等待模块响应response = ser.read(12) # 读取12字节的响应数据if len(response) == 12 and response[0] == 0x5A and response[1] == 0x5A:# 解析温度(第4和5字节)temperature = ((response[4] << 8) | response[5]) / 100.0# 解析湿度(第6和7字节)humidity = ((response[6] << 8) | response[7]) / 100.0# 解析气压(第8和9字节)pressure = ((response[8] << 8) | response[9]) / 100.0# 解析海拔(第10和11字节)altitude = ((response[10] << 8) | response[11]) / 100.0print(f"温度: {temperature} °C")print(f"湿度: {humidity} %")print(f"气压: {pressure} hPa")print(f"海拔: {altitude} m")else:print("未收到完整的响应数据")except Exception as e:print(f"通信错误: {e}")if __name__ == "__main__":while True:read_environment()time.sleep(1)