Read SHT21 Sensor From Raspberry Pi

written on Monday, February 06, 2017 by

To read a SHT21 temperature/humidity sensor from Raspbian Linux on the Raspberry Pi, first enable the I²C bus via raspi-config and reboot. Then, load the sht21 kernel module:

$ sudo su
# modprobe sht21

(To make the change permanent, run echo "sht21" > /etc/modules-load.d/sht21.conf as root.)

If you want to verify that the sensor is wired up correctly, install i2c-tools and run i2cdetect -y 1 0x40 0x4f. If everything is fine, you should see it at the address 0x40:

# i2cdetect -y 1 0x40 0x4f
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

Since a computer can have multiple I²C busses, the kernel needs to know to which one the sensor is connected. We therefore register the sensor at address 0x40 with the I²C sysfs device:

# echo sht21 0x40 > /sys/bus/i2c/devices/i2c-1/new_device

Now the sensor values are exposed at /sys/class/hwmon/hwmon0:

# ls /sys/class/hwmon/hwmon0
device           name   subsystem    uevent
humidity1_input  power  temp1_input

To read the current temperature:

# cat /sys/class/hwmon/hwmon0/temp1_input

...and the relative humidity:

# cat /sys/class/hwmon/hwmon0/humidity1_input

If you have lm-sensors installed, you can also run the sensors command to get a sensor reading:

# sensors
Adapter: 3f804000.i2c
temp1:        +30.8°C
humidity1:     33.3 %RH

..and if you use collectd to log system metrics, load the sensors plugin like this:

echo "LoadPlugin sensors" >> /etc/collectd/collectd.conf
Flattr this!

This entry was tagged kernel, linux, raspberry_pi, sensirion and sensors

comments powered by Disqus