Introduction: XY-MD02 Temperature and Humidity Sensor Module Modbus RS485 Raspberry Pi

About: Hello! My name is FuzzyPotato, I have a passion for electronics, Python programming, and DIY projects. I have always been fascinated by the way things work, and I have a love for using technology to solve prob…

Reading the XY-MD02 Temperature and Humidity Sensor with a Raspberry Pi

Supplies

  • XY-MD02 Temperature and Humidity Sensor Module
  • Raspberry Pi
  • USB to RS485 converter. I like this one (https://core-electronics.com.au/industrial-usb-to-rs485-converter.html)
  • Power supply

Step 1: Wiring

  1. Connect the XY-MD02 Temperature and Humidity Sensor to the USB to RS485 converter.
  2. XY-MD02 B- to Converter B-
  3. XY-MD02 A+ to Converter A+
  4. XY-MD02 to 12v
  5. XY-MD02 to Converter ground
  6. Connect power supply to the 12v and the ground
  7. Plug the USB to RS485 converter into the Raspberry Pi.

Step 2: Setup

  1. Open your IDE and create a new sketch. (I am using Thonny)
  2. Copy and paste the code provided into the sketch.
  3. Check the device port.
  4. The code is expecting that your device port is port='/dev/ttyUSB0'. This works most of the time.
  5. If you have trouble you can search for the converter by unplugging it and the running this command " ls /dev/tty* " in a terminal, plug the device back in, and run the command again. The new converter will be the one that wasn't listed before. 

Step 3: Code

import serial

import time


temp_ref_frame = [0x01, 0x04, 0x00, 0x01, 0x00, 0x01, 0x60, 0x0a] # Request frame for temp sensor

humid_ref_frame = [0x01, 0x04, 0x00, 0x02, 0x00, 0x01, 0x90, 0x0a] # Request frame for humidity sensor


ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600) # Remember, you might need to replace '/dev/ttyUSB0' with the port name where your USB to RS485 converter is connected


def get_temp():

  ser.write(bytes(temp_ref_frame))

  time.sleep(1)

  buf = ser.read(7)

  temp_value = (buf[3] << 8) | buf[4]

  temperature = temp_value / 10.0

  return temperature



def get_humidity():

  ser.write(bytes(humid_ref_frame))

  time.sleep(1)

  buf = ser.read(7)

  humid_value = (buf[3] << 8) | buf[4]

  humidity = humid_value / 10.0

  return humidity



while True:


  print("-----------------------------------------------")

  print("Temp: ", get_temp())

  time.sleep(3)


  print("-----------------------------------------------")

  print("Humidity: " , get_humidity())

  time.sleep(3)


Step 4: Test

  1. Run the code
  2. You should see the Temperature and humidity values in the Shell monitor

Step 5: Conclusion

Congratulations, now you can can read the temperature and humidity values from the XY-MD02 Temperature and Humidity Sensor and display it on the Shell Monitor.

You can now use the code in your own projects.

Happy tinkering!