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

by FuzzyPotato in Circuits > Raspberry Pi

3180 Views, 3 Favorites, 0 Comments

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

XY-MD02-01.jpg
USB-RS485-Converter-1.jpg
rpi_rpicase-100851665-orig.jpg

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

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.

Setup

FindUSBDeviceScreenshotV4.jpg
  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. 

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)


Test

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

Conclusion

Celebrate-free-celebration-clip-art-pictures-2.jpg

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!