2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2016 Michael Zhilin <mizhka@freebsd.org> All rights reserved.
5 * Copyright (c) 2019 Ian Lepore <ian@freebsd.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * GPIOTHS - Temp/Humidity sensor over GPIO.
32 * This is driver for Temperature & Humidity sensor which provides digital
33 * output over single-wire protocol from embedded 8-bit microcontroller.
34 * Note that it uses a custom single-wire protocol, it is not 1-wire(tm).
36 * This driver supports the following chips:
37 * DHT11: Temp 0c to 50c +-2.0c, Humidity 20% to 90% +-5%
38 * DHT12: Temp -20c to 60c +-0.5c, Humidity 20% to 95% +-5%
39 * DHT21: Temp -40c to 80c +-0.3c, Humidity 0% to 100% +-3%
40 * DHT22: Temp -40c to 80c +-0.3c, Humidity 0% to 100% +-2%
41 * AM2301: Same as DHT21, but also supports i2c interface.
42 * AM2302: Same as DHT22, but also supports i2c interface.
44 * Temp/Humidity sensor can't be discovered automatically, please specify hints
45 * as part of loader or kernel configuration:
46 * hint.gpioths.0.at="gpiobus0"
47 * hint.gpioths.0.pins=<PIN>
49 * Or configure via FDT data.
52 #include <sys/cdefs.h>
53 #include <sys/param.h>
54 #include <sys/kernel.h>
57 #include <sys/module.h>
58 #include <sys/errno.h>
59 #include <sys/systm.h>
60 #include <sys/sysctl.h>
61 #include <sys/taskqueue.h>
63 #include <dev/gpio/gpiobusvar.h>
66 #include <dev/ofw/ofw_bus.h>
67 #include <dev/ofw/ofw_bus_subr.h>
69 static struct ofw_compat_data compat_data[] = {
73 OFWBUS_PNP_INFO(compat_data);
74 SIMPLEBUS_PNP_INFO(compat_data);
77 #define PIN_IDX 0 /* Use the first/only configured pin. */
79 #define GPIOTHS_POLLTIME 5 /* in seconds */
81 #define GPIOTHS_DHT_STARTCYCLE 20000 /* 20ms = 20000us */
82 #define GPIOTHS_DHT_TIMEOUT 1000 /* 1ms = 1000us */
83 #define GPIOTHS_DHT_CYCLES 41
84 #define GPIOTHS_DHT_ONEBYTEMASK 0xFF
86 struct gpioths_softc {
92 struct timeout_task task;
97 gpioths_probe(device_t dev)
102 * By default we only bid to attach if specifically added by our parent
103 * (usually via hint.gpioths.#.at=busname). On FDT systems we bid as
104 * the default driver based on being configured in the FDT data.
106 rv = BUS_PROBE_NOWILDCARD;
109 if (ofw_bus_status_okay(dev) &&
110 ofw_bus_search_compatible(dev, compat_data)->ocd_data)
111 rv = BUS_PROBE_DEFAULT;
114 device_set_desc(dev, "DHT11/DHT22 Temperature and Humidity Sensor");
120 gpioths_dht_timeuntil(struct gpioths_softc *sc, bool lev, uint32_t *time)
125 for (i = 0; i < GPIOTHS_DHT_TIMEOUT; i++) {
126 gpio_pin_is_active(sc->pin, &cur_level);
127 if (cur_level == lev) {
140 gpioths_dht_initread(struct gpioths_softc *sc)
144 * According to specifications we need to drive the data line low for at
145 * least 20ms then drive it high, to wake up the chip and signal it to
146 * send a measurement. After sending this start signal, we switch the
147 * pin back to input so the device can begin talking to us.
149 gpio_pin_setflags(sc->pin, GPIO_PIN_OUTPUT);
150 gpio_pin_set_active(sc->pin, false);
151 pause_sbt("gpioths", ustosbt(GPIOTHS_DHT_STARTCYCLE), C_PREL(2), 0);
152 gpio_pin_set_active(sc->pin, true);
153 gpio_pin_setflags(sc->pin, GPIO_PIN_INPUT);
157 gpioths_dht_readbytes(struct gpioths_softc *sc)
159 uint32_t calibrations[GPIOTHS_DHT_CYCLES];
160 uint32_t intervals[GPIOTHS_DHT_CYCLES];
161 uint32_t err, avglen, value;
163 int i, negmul, offset, size, tmphi, tmplo;
165 gpioths_dht_initread(sc);
167 err = gpioths_dht_timeuntil(sc, false, NULL);
169 device_printf(sc->dev, "err(START) = %d\n", err);
173 /* reading - 41 cycles */
174 for (i = 0; i < GPIOTHS_DHT_CYCLES; i++) {
175 err = gpioths_dht_timeuntil(sc, true, &calibrations[i]);
177 device_printf(sc->dev, "err(CAL, %d) = %d\n", i, err);
180 err = gpioths_dht_timeuntil(sc, false, &intervals[i]);
182 device_printf(sc->dev, "err(INTERVAL, %d) = %d\n", i, err);
187 /* Calculate average data calibration cycle length */
189 for (i = 1; i < GPIOTHS_DHT_CYCLES; i++)
190 avglen += calibrations[i];
192 avglen = avglen / (GPIOTHS_DHT_CYCLES - 1);
197 size = sizeof(value) * 8;
198 for (i = offset; i < size + offset; i++) {
200 if (intervals[i] > avglen)
206 offset = sizeof(value) * 8 + 1;
207 size = sizeof(crc) * 8;
208 for (i = offset; i < size + offset; i++) {
210 if (intervals[i] > avglen)
215 for (i = 0; i < sizeof(value); i++)
216 calc += (value >> (8*i)) & GPIOTHS_DHT_ONEBYTEMASK;
220 for (i = 0; i < GPIOTHS_DHT_CYCLES; i++)
221 device_printf(sc->dev, "%d: %d %d\n", i, calibrations[i],
224 device_printf(sc->dev, "len=%d, data=%x, crc=%x/%x\n", avglen, value, crc,
226 #endif /* GPIOTHS_DEBUG */
235 * For DHT11/12, the values are split into 8 bits of integer and 8 bits
236 * of fractional tenths. On DHT11 the fraction bytes are always zero.
237 * On DHT12 the sign bit is in the high bit of the fraction byte.
238 * - DHT11: 0HHHHHHH 00000000 00TTTTTT 00000000
239 * - DHT12: 0HHHHHHH 0000hhhh 00TTTTTT s000tttt
241 * For DHT21/21, the values are are encoded in 16 bits each, with the
242 * temperature sign bit in the high bit. The values are tenths of a
243 * degree C and tenths of a percent RH.
244 * - DHT21: 000000HH HHHHHHHH s00000TT TTTTTTTT
245 * - DHT22: 000000HH HHHHHHHH s00000TT TTTTTTTT
247 * For all devices, some bits are always zero because of the range of
248 * values supported by the device.
250 * We figure out how to decode things based on the high byte of the
251 * humidity. A DHT21/22 cannot report a value greater than 3 in
252 * the upper bits of its 16-bit humidity. A DHT11/12 should not report
253 * a value lower than 20. To allow for the possibility that a device
254 * could report a value slightly out of its sensitivity range, we split
255 * the difference and say if the value is greater than 10 it must be a
256 * DHT11/12 (that would be a humidity over 256% on a DHT21/22).
258 #define DK_OFFSET 2731 /* Offset between K and C, in decikelvins. */
259 if ((value >> 24) > 10) {
261 tmphi = (value >> 8) & 0x3f;
262 tmplo = value & 0x0f;
263 negmul = (value & 0x80) ? -1 : 1;
264 sc->temp = DK_OFFSET + (negmul * (tmphi * 10 + tmplo));
265 sc->hum = (value >> 24) & 0x7f;
268 negmul = (value & 0x8000) ? -1 : 1;
269 sc->temp = DK_OFFSET + (negmul * (value & 0x03ff));
270 sc->hum = ((value >> 16) & 0x03ff) / 10;
277 device_printf(dev, "fails=%d, temp=%d, hum=%d\n", sc->fails,
279 #endif /* GPIOTHS_DEBUG */
288 gpioths_poll(void *arg, int pending __unused)
290 struct gpioths_softc *sc;
292 sc = (struct gpioths_softc *)arg;
294 gpioths_dht_readbytes(sc);
296 taskqueue_enqueue_timeout_sbt(taskqueue_thread, &sc->task,
297 GPIOTHS_POLLTIME * SBT_1S, 0, C_PREL(3));
301 gpioths_attach(device_t dev)
303 struct gpioths_softc *sc;
304 struct sysctl_ctx_list *ctx;
305 struct sysctl_oid *tree;
308 sc = device_get_softc(dev);
309 ctx = device_get_sysctl_ctx(dev);
310 tree = device_get_sysctl_tree(dev);
314 TIMEOUT_TASK_INIT(taskqueue_thread, &sc->task, 0, gpioths_poll, sc);
317 /* Try to configure our pin from fdt data on fdt-based systems. */
318 err = gpio_pin_get_by_ofw_idx(dev, ofw_bus_get_node(dev), PIN_IDX,
324 * If we didn't get configured by fdt data and our parent is gpiobus,
325 * see if we can be configured by the bus (allows hinted attachment even
326 * on fdt-based systems).
329 strcmp("gpiobus", device_get_name(device_get_parent(dev))) == 0)
330 err = gpio_pin_get_by_child_index(dev, PIN_IDX, &sc->pin);
332 /* If we didn't get configured by either method, whine and punt. */
334 device_printf(sc->dev,
335 "cannot acquire gpio pin (config error)\n");
340 * Ensure we have control of our pin, and preset the data line to its
341 * idle condition (high). Leave the line in input mode, relying on the
342 * external pullup to keep the line high while idle.
344 err = gpio_pin_setflags(sc->pin, GPIO_PIN_OUTPUT);
346 device_printf(dev, "gpio_pin_setflags(OUT) = %d\n", err);
349 err = gpio_pin_set_active(sc->pin, true);
351 device_printf(dev, "gpio_pin_set_active(false) = %d\n", err);
354 err = gpio_pin_setflags(sc->pin, GPIO_PIN_INPUT);
356 device_printf(dev, "gpio_pin_setflags(IN) = %d\n", err);
361 * Do an initial read so we have correct values for reporting before
362 * registering the sysctls that can access those values. This also
363 * schedules the periodic polling the driver does every few seconds to
364 * update the sysctl variables.
368 sysctl_add_oid(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "temperature", \
369 CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
370 &sc->temp, 0, sysctl_handle_int, "IK", "temperature", NULL);
372 SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "humidity",
373 CTLFLAG_RD, &sc->hum, 0, "relative humidity(%)");
375 SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "fails",
376 CTLFLAG_RD, &sc->fails, 0,
377 "failures since last successful read");
383 gpioths_detach(device_t dev)
385 struct gpioths_softc *sc;
387 sc = device_get_softc(dev);
388 gpio_pin_release(sc->pin);
389 sc->detaching = true;
390 while (taskqueue_cancel_timeout(taskqueue_thread, &sc->task, NULL) != 0)
391 taskqueue_drain_timeout(taskqueue_thread, &sc->task);
397 static device_method_t gpioths_methods[] = {
398 /* Device interface */
399 DEVMETHOD(device_probe, gpioths_probe),
400 DEVMETHOD(device_attach, gpioths_attach),
401 DEVMETHOD(device_detach, gpioths_detach),
406 DEFINE_CLASS_0(gpioths, gpioths_driver, gpioths_methods, sizeof(struct gpioths_softc));
409 DRIVER_MODULE(gpioths, simplebus, gpioths_driver, 0, 0);
412 DRIVER_MODULE(gpioths, gpiobus, gpioths_driver, 0, 0);
413 MODULE_DEPEND(gpioths, gpiobus, 1, 1, 1);