Last active
June 7, 2024 08:31
-
-
Save fabaff/18024d833cb619e3df334a815c4d9eef to your computer and use it in GitHub Desktop.
Get the temperature and the humidity from a XY-MD02 sensor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Get the temperature and the humidity from a XY-MD02 sensor.""" | |
from pymodbus.client import ModbusSerialClient as ModbusClient | |
from pymodbus.constants import Endian | |
from pymodbus.payload import BinaryPayloadDecoder | |
SERIAL_PORT = "/dev/ttyUSB0" | |
BAUDRATE = 9600 | |
SLAVE_ID = 1 | |
client = ModbusClient(method="rtu", port=SERIAL_PORT, baudrate=BAUDRATE) | |
client.connect() | |
def read_data(address): | |
response = client.read_input_registers(address=address, slave=SLAVE_ID, unit=1) | |
if response.isError(): | |
print(f"Error reading data: {response}") | |
return None | |
else: | |
decoder = BinaryPayloadDecoder.fromRegisters( | |
response.registers, byteorder=Endian.BIG | |
) | |
data = decoder.decode_16bit_int() / 10.0 | |
return data | |
if __name__ == "__main__": | |
try: | |
# Input register 0x0001 | |
temperature = read_data(1) | |
# Input register 0x0002 | |
humidity = read_data(2) | |
if temperature is not None: | |
print(f"Temperature: {temperature} °C") | |
if humidity is not None: | |
print(f"Humidity: {humidity} %") | |
finally: | |
client.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment