HTU31D Humidity Sensor

The HTU31D [1] is an I2C digital humidity sensor with a typical accuracy of ±2% at 20% to 100% relative humidity. It also provides temperature with an accuracy of ±0.2°C from 0 to 100°C.

A breakout is available from Adafruit [2]:

HTU31D.jpg

The I2C address is #x40 or 64.

Reading the temperature

The following floating-point function reads the temperature in degrees Celsius:

(defun htu31d-temp ()
  (with-i2c (s #x40)
    (write-byte #x40 s) ; conversion
    (restart-i2c s)
    (delay 20)
    (write-byte #x00 s) ; read temperature
    (restart-i2c s 2)
    (- (* 165
          (/ (logior (ash (read-byte s) 8) (read-byte s)) 65535))
       40)))

For example:

> (htu31d-temp)
22.3594

Reading the humidity

The following floating-point function reads the humidity in %RH:

(defun htu31d-humidity ()
  (with-i2c (s #x40)
    (write-byte #x40 s) ; conversion
    (restart-i2c s)
    (delay 20)
    (write-byte #x10 s) ; read humidity
    (restart-i2c s 2)
    (* 100 (/ (logior (ash (read-byte s) 8) (read-byte s)) 65535))))

For example:

> (htu31d-humidity)
60.0412

Enabling the heater

The sensor also incorporates a heater, to combat condensation. Here's a routine to enable or disable the heater:

(defun htu31d-heater (on)
  (with-i2c (s #x40)
    (write-byte (if on #x04 #x02) s)))

To turn the heater on call:

(htu31d-heater t)

or to turn if off call:

(htu31d-heater nil)

  1. ^ HTU31D Datasheet on TTI.com.
  2. ^ Adafruit HTU31D Temperature & Humidity Sensor Breakout Board on Adafruit.