2

I'm trying to use a Raspberry Pi 4 to read an I2C temperature and humidity sensor. The part I'm using is a module from Grove based on the DHT20 sensor. Here's a link to a page about the module

I need some help programming the I2C communication. The specs sheet for the sensor explains the frames that are needed for correct communication (see page 8):

I would be grateful if someone could show me the Python code needed to get a sensor reading. Preferably this would be based on the smbus package, but I will be grateful for any solution (based on whatever package you prefer). I understand that there are many answers about the DHT11 and DHT22 sensors, but these older models have one-wire logic whereas the newer DHT20 has I2C.

Rohit Gupta
  • 343
  • 2
  • 4
  • 11

3 Answers3

4

First start by finding the I2C address of your sensor. Here's an explanation of how to do that: https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-i2c (look under the section "Testing I2C").

Once you have the address, try the following Python code:

import time
import smbus

address = 0x38 #Put your device's address here

i2cbus = smbus.SMBus(1) time.sleep(0.5)

data = i2cbus.read_i2c_block_data(address,0x71,1) if (data[0] | 0x08) == 0: print('Initialization error')

i2cbus.write_i2c_block_data(address,0xac,[0x33,0x00]) time.sleep(0.1)

data = i2cbus.read_i2c_block_data(address,0x71,7)

Traw = ((data[3] & 0xf) << 16) + (data[4] << 8) + data[5] temperature = 200float(Traw)/2*20 - 50

Hraw = ((data[3] & 0xf0) >> 4) + (data[1] << 12) + (data[2] << 4) humidity = 100float(Hraw)/2*20

print(temperature) print(humidity)

ultracold
  • 56
  • 1
0

It seems like smbus is deprecated, but smbus2 works as well. Just adapt the code of @ultracold:

import time
import smbus2

address = 0x38 #Put your device's address here

i2cbus = smbus2.SMBus(1) time.sleep(0.5)

data = i2cbus.read_i2c_block_data(address,0x71,1) if (data[0] | 0x08) == 0: print('Initialization error')

i2cbus.write_i2c_block_data(address,0xac,[0x33,0x00]) time.sleep(0.1)

data = i2cbus.read_i2c_block_data(address,0x71,7)

Traw = ((data[3] & 0xf) << 16) + (data[4] << 8) + data[5] temperature = 200float(Traw)/2*20 - 50

Hraw = ((data[3] & 0xf0) >> 4) + (data[1] << 12) + (data[2] << 4) humidity = 100float(Hraw)/2*20

print(temperature) print(humidity)

ucczs
  • 101
0

Thanks to ultracold and ucczs for great answers! The code worked for me. I just changed the last two lines to format the output:

print("Temperature:", "%.2f" % temperature + '\xb0', "C")
print("Humidity:   ", "%.2f" % humidity, " %")