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
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
- Connect the XY-MD02 Temperature and Humidity Sensor to the USB to RS485 converter.
- XY-MD02 B- to Converter B-
- XY-MD02 A+ to Converter A+
- XY-MD02 to 12v
- XY-MD02 to Converter ground
- Connect power supply to the 12v and the ground
- Plug the USB to RS485 converter into the Raspberry Pi.
Setup
- Open your IDE and create a new sketch. (I am using Thonny)
- Copy and paste the code provided into the sketch.
- Check the device port.
- The code is expecting that your device port is port='/dev/ttyUSB0'. This works most of the time.
- 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
- Run the code
- You should see the Temperature and humidity values in the Shell monitor
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!