Opensourcetechブログ

OpensourcetechによるNGINX/Kubernetes/Zabbix/Neo4j/Linuxなどオープンソース技術に関するブログです。

Raspberry Pi(zero)にデジタル温湿度センサー DHT11を接続し、温度&湿度を測定する!

こんにちは、LinuCエバンジェリストこと、鯨井貴博@opensourcetechです。

 

今回は、Raspberry Pi(zero)にデジタル温湿度センサー DHT11を接続し、

温度・湿度を測定してみます。

 

 

DHT11

秋葉原の秋月電子で 300円で売ってました。

温湿度センサ モジュール DHT11: センサ一般 秋月電子通商-電子部品・ネット通販

http://akizukidenshi.com/download/ds/aosong/DHT11_20180119.pdf

 

なお、これの上位モデルとしてDHT22(AM2302)があり、高精度で測定ができるようです。

温湿度センサ モジュール AM2302: センサ一般 秋月電子通商-電子部品・ネット通販

 

Linux Kernel のソースコードを見ると、温度・湿度ともに1,000倍にして

数値として出力してくれる模様(多分w)。

linux/dht11.c at master · torvalds/linux · GitHub

 

 

接続の準備

Raspbianの/boot/confit.txtで、DHT11に関する情報を追記します。

pi@raspberrypi:~ $ vi /boot/config.txt
pi@raspberrypi:~ $ cat /boot/config.txt
# For more options and information see
# http://rpf.io/configtxt
# Some settings may impact device functionality. See link above for details

# uncomment if you get no picture on HDMI for a default "safe" mode
#hdmi_safe=1

# uncomment this if your display has a black border of unused pixels visible
# and your display can output without overscan
#disable_overscan=1

# uncomment the following to adjust overscan. Use positive numbers if console
# goes off screen, and negative if there is too much border
#overscan_left=16
#overscan_right=16
#overscan_top=16
#overscan_bottom=16

# uncomment to force a console size. By default it will be display's size minus
# overscan.
#framebuffer_width=1280
#framebuffer_height=720

# uncomment if hdmi display is not detected and composite is being output
#hdmi_force_hotplug=1

# uncomment to force a specific HDMI mode (this will force VGA)
#hdmi_group=1
#hdmi_mode=1

# uncomment to force a HDMI mode rather than DVI. This can make audio work in
# DMT (computer monitor) modes
#hdmi_drive=2

# uncomment to increase signal to HDMI, if you have interference, blanking, or
# no display
#config_hdmi_boost=4

# uncomment for composite PAL
#sdtv_mode=2

#uncomment to overclock the arm. 700 MHz is the default.
#arm_freq=800

# Uncomment some or all of these to enable the optional hardware interfaces
#dtparam=i2c_arm=on
#dtparam=i2s=on
#dtparam=spi=on

# Uncomment this to enable the lirc-rpi module
#dtoverlay=lirc-rpi
dtparam=audio=on
dtoverlay=dwc2
dtoverlay=dht11 ・・・追記

 

 

 modprobeで dht11を読み込みます。

pi@raspberrypi:~ $ sudo modprobe dht11
pi@raspberrypi:~ $ lsmod
Module Size Used by
dht11 3924 0 ・・・これです
industrialio 63573 1 dht11
bluetooth 366751 0
ecdh_generic 17649 1 bluetooth
fuse 92214 3
cfg80211 542242 0
rfkill 21476 3 bluetooth,cfg80211
snd_bcm2835 23054 1
snd_pcm 89526 1 snd_bcm2835
snd_timer 22396 1 snd_pcm
snd 59578 5 snd_timer,snd_bcm2835,snd_pcm
fixed 3033 0
uio_pdrv_genirq 3718 0
uio 9901 1 uio_pdrv_genirq
i2c_dev 6674 0
usb_f_ecm 7416 1
g_ether 5037 0
usb_f_rndis 17908 2 g_ether
u_ether 12901 3 usb_f_ecm,g_ether,usb_f_rndis
libcomposite 48180 3 usb_f_ecm,g_ether,usb_f_rndis
dwc2 127674 0
udc_core 38830 5 usb_f_ecm,dwc2,u_ether,usb_f_rndis,libcomposite
ip_tables 12395 0
x_tables 21842 1 ip_tables
ipv6 401548 18

 

 

ちなみに、/boot/overlays/READMEを見ると、/boot/config.txtへの追記方法の説明が観れます。

pi@raspberrypi:~ $ cat /boot/overlays/README
Introduction
============

This directory contains Device Tree overlays. Device Tree makes it possible
to support many hardware configurations with a single kernel and without the
need to explicitly load or blacklist kernel modules. Note that this isn't a
"pure" Device Tree configuration (c.f. MACH_BCM2835) - some on-board devices
are still configured by the board support code, but the intention is to
eventually reach that goal.

On Raspberry Pi, Device Tree usage is controlled from /boot/config.txt. By
default, the Raspberry Pi kernel boots with device tree enabled. You can
completely disable DT usage (for now) by adding:

device_tree=

to your config.txt, which should cause your Pi to revert to the old way of
doing things after a reboot.

In /boot you will find a .dtb for each base platform. This describes the
hardware that is part of the Raspberry Pi board. The loader (start.elf and its
siblings) selects the .dtb file appropriate for the platform by name, and reads
it into memory. At this point, all of the optional interfaces (i2c, i2s, spi)
are disabled, but they can be enabled using Device Tree parameters:

dtparam=i2c=on,i2s=on,spi=on

However, this shouldn't be necessary in many use cases because loading an
overlay that requires one of those interfaces will cause it to be enabled
automatically, and it is advisable to only enable interfaces if they are
needed.

Configuring additional, optional hardware is done using Device Tree overlays
(see below).

GPIO numbering uses the hardware pin numbering scheme (aka BCM scheme) and
not the physical pin numbers.

raspi-config
============

The Advanced Options section of the raspi-config utility can enable and disable
Device Tree use, as well as toggling the I2C and SPI interfaces. Note that it
is possible to both enable an interface and blacklist the driver, if for some
reason you should want to defer the loading.

Modules
=======

As well as describing the hardware, Device Tree also gives enough information
to allow suitable driver modules to be located and loaded, with the corollary
that unneeded modules are not loaded. As a result it should be possible to
remove lines from /etc/modules, and /etc/modprobe.d/raspi-blacklist.conf can
have its contents deleted (or commented out).

Using Overlays
==============

Overlays are loaded using the "dtoverlay" directive. As an example, consider
the popular lirc-rpi module, the Linux Infrared Remote Control driver. In the
pre-DT world this would be loaded from /etc/modules, with an explicit
"modprobe lirc-rpi" command, or programmatically by lircd. With DT enabled,
this becomes a line in config.txt:

dtoverlay=lirc-rpi

This causes the file /boot/overlays/lirc-rpi.dtbo to be loaded. By
default it will use GPIOs 17 (out) and 18 (in), but this can be modified using
DT parameters:

dtoverlay=lirc-rpi,gpio_out_pin=17,gpio_in_pin=13

Parameters always have default values, although in some cases (e.g. "w1-gpio")
it is necessary to provided multiple overlays in order to get the desired
behaviour. See the list of overlays below for a description of the parameters
and their defaults.

The Overlay and Parameter Reference
===================================

N.B. When editing this file, please preserve the indentation levels to make it
simple to parse programmatically. NO HARD TABS.


Name: <The base DTB>
Info: Configures the base Raspberry Pi hardware
Load: <loaded automatically>
Params:
audio Set to "on" to enable the onboard ALSA audio
interface (default "off")

eee Enable Energy Efficient Ethernet support for
compatible devices (default "on"). See also
"tx_lpi_timer".

eth_led0 Set mode of LED0 (usually orange) (default
"1"). The legal values are:
0=link/activity 1=link1000/activity
2=link100/activity 3=link10/activity
4=link100/1000/activity 5=link10/1000/activity
6=link10/100/activity 14=off 15=on

eth_led1 Set mode of LED1 (usually green) (default
"6"). See eth_led0 for legal values.

i2c_arm Set to "on" to enable the ARM's i2c interface
(default "off")

i2c_vc Set to "on" to enable the i2c interface
usually reserved for the VideoCore processor
(default "off")

i2c An alias for i2c_arm

i2c_arm_baudrate Set the baudrate of the ARM's i2c interface
(default "100000")

i2c_vc_baudrate Set the baudrate of the VideoCore i2c interface
(default "100000")

i2c_baudrate An alias for i2c_arm_baudrate

i2s Set to "on" to enable the i2s interface
(default "off")

spi Set to "on" to enable the spi interfaces
(default "off")

random Set to "on" to enable the hardware random
number generator (default "on")

sd_overclock Clock (in MHz) to use when the MMC framework
requests 50MHz

sd_force_pio Disable DMA support for SD driver (default off)

sd_pio_limit Number of blocks above which to use DMA for
SD card (default 1)

sd_debug Enable debug output from SD driver (default off)

tx_lpi_timer Set the delay in microseconds between going idle
and entering the low power state (default 600).
Requires EEE to be enabled - see "eee".

uart0 Set to "off" to disable uart0 (default "on")

uart1 Set to "on" or "off" to enable or disable uart1
(default varies)

watchdog Set to "on" to enable the hardware watchdog
(default "off")

act_led_trigger Choose which activity the LED tracks.
Use "heartbeat" for a nice load indicator.
(default "mmc")

act_led_activelow Set to "on" to invert the sense of the LED
(default "off")
N.B. For Pi3 see pi3-act-led overlay.

act_led_gpio Set which GPIO to use for the activity LED
(in case you want to connect it to an external
device)
(default "16" on a non-Plus board, "47" on a
Plus or Pi 2)
N.B. For Pi3 see pi3-act-led overlay.

pwr_led_trigger
pwr_led_activelow
pwr_led_gpio
As for act_led_*, but using the PWR LED.
Not available on Model A/B boards.

N.B. It is recommended to only enable those interfaces that are needed.
Leaving all interfaces enabled can lead to unwanted behaviour (i2c_vc
interfering with Pi Camera, I2S and SPI hogging GPIO pins, etc.)
Note also that i2c, i2c_arm and i2c_vc are aliases for the physical
interfaces i2c0 and i2c1. Use of the numeric variants is still possible
but deprecated because the ARM/VC assignments differ between board
revisions. The same board-specific mapping applies to i2c_baudrate,
and the other i2c baudrate parameters.


Name: adau1977-adc
Info: Overlay for activation of ADAU1977 ADC codec over I2C for control
and I2S for data.
Load: dtoverlay=adau1977-adc
Params: <None>

.
.
.
省略
.
.
.

Name: dht11
Info: Overlay for the DHT11/DHT21/DHT22 humidity/temperature sensors
Also sometimes found with the part number(s) AM230x.
Load: dtoverlay=dht11,<param>=<val>
Params: gpiopin GPIO connected to the sensor's DATA output.
(default 4)  ・・・・・ここが DHT11に関する部分!

.
.
.
省略
.
.
.

Troubleshooting
===============

If you are experiencing problems that you think are DT-related, enable DT
diagnostic output by adding this to /boot/config.txt:

dtdebug=on

and rebooting. Then run:

sudo vcdbg log msg

and look for relevant messages.

Further reading
===============

This is only meant to be a quick introduction to the subject of Device Tree on
Raspberry Pi. There is a more complete explanation here:

http://www.raspberrypi.org/documentation/configuration/device-tree.md

 

そして、Raspbianを再起動します。

 

 

配線

詳細は、DHT11のデータシートを見てもらえばいいですが、以下のように接続してます。

f:id:opensourcetech:20181125235724p:plain

f:id:opensourcetech:20190205081741j:plain



 

必要なもの

・Raspberry Pi zero

・DHT11(温湿度センサー)

・ブレッドボード

・抵抗(5.1kΩに合うように組み合わせるなど)

・ジャンパーコード(オスーオス、オスーメス)

 

 

温度・湿度の測定

Raspbian上の 「/sys/bus/iio/devices/iio:device0/in_temp_input」で温度、「/sys/bus/iio/devices/iio:device0/in_humidityrelative_input」で湿度の情報が取得できます。

 ※それぞれ 1/1,000すれば、温度(℃)・湿度(%)になります。

pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio\:device0/in_temp_input
20000 ・・・温度20℃
pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio\:device0/in_humidityrelative_input
56000 ・・・湿度56%

 

 

試しに、お湯の入ったコップの上にセンサーを置いてみました。

f:id:opensourcetech:20181125231706j:plain

 

 温度32℃・湿度68%に変化。きちんと測定できているようです。

pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio\:device0/in_temp_input
32000
pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio\:device0/in_humidityrelative_input
68000

 

 

気になったこと

以下を実行すると、そこそこの確率で「error」となることがある。

pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio\:device0/in_temp_input
pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio\:device0/in_humidityrelative_input

 

errorの回避策としては、一回ではなく複数回繰り返し実行すること。

そうすると、値を取得することができました。

crontabなどで定期的に取得する場合、以下のようなスクリプトが便利です。

https://github.com/kujiraitakahiro/RaspberryPi/blob/master/DHT11.sh

 

 

なお、上記に関連しているかもしれない情報として 以下のものを見つけました。

・タイマーをmsleepからusleepに変更したPatch

[PATCH] iio: dht11: Use usleep_range instead of msleep for start signal — Linux IIO Development

・データの取得は繰り返し複数回行え的なことが書いてある

device-tree for DHT11 Temperature/Humidity sensor - Raspberry Pi Forums

・データの取得は2回行え的なことが書いてある

http://akizukidenshi.com/download/ds/aosong/DHT11_20180119.pdf

 

 

 

www.slideshare.net

github.com

www.facebook.com

twitter.com

www.instagram.com

 

 

にほんブログ村 IT技術ブログ Linuxへ
Linux

にほんブログ村 IT技術ブログ オープンソースへ
オープンソース

 

 

Opensourcetech by Takahiro Kujirai