【樹莓派】使用DHT11連接樹莓派讀取傳感器數字並通過0.96寸屏展示

設備

  • 樹莓派3b+
  • 溫溼度傳感器DHT11

在這裏插入圖片描述

接線

VCC - 電源3.3v或者5v
data - 數據讀取
GND - 接地

這個的接線方式和上次的接線很像,其實其他的也都差不多,電源正負和數據讀取寫入

讀取

在上面的接線中,我把DHT11放在了22號針腳上,所以下面的針腳號都是22,如果你接在了其他部分,注意修改~

使用官方庫

官方的安裝方式和上次用顯示屏的方式一樣,都是clone,安裝,執行

git clone git://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT/
sudo python setup.py install
cd examples/
python AdafruitDHT.py 11 22

最終的結果是

Temp=25.0*  Humidity=22.0%

如果是用python3,就把上面的python改成python3即可。

sudo python3 setup.py install
python3 AdafruitDHT.py 11 22

也是可以執行的。

AdafruitDHT.py文件內容如下

#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys

import Adafruit_DHT


# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
                '22': Adafruit_DHT.DHT22,
                '2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
    sensor = sensor_args[sys.argv[1]]
    pin = sys.argv[2]
else:
    print('Usage: sudo ./Adafruit_DHT.py [11|22|2302] <GPIO pin number>')
    print('Example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO pin #4')
    sys.exit(1)

# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32

# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
    print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))
else:
    print('Failed to get reading. Try again!')
    sys.exit(1)

使用GPIO讀取

我們也可以直接通過python直接讀取GPIO針腳的數據

 
import RPi.GPIO as GPIO
import time
 
channel = 22			#引腳號
data = []			#溫溼度值
j = 0				#計數器
 
GPIO.setmode(GPIO.BCM)		#以BCM編碼格式
 
time.sleep(1)			#時延一秒
 
GPIO.setup(channel, GPIO.OUT)
 
GPIO.output(channel, GPIO.LOW)
time.sleep(0.02)		#給信號提示傳感器開始工作
GPIO.output(channel, GPIO.HIGH)
 
GPIO.setup(channel, GPIO.IN)
 
while GPIO.input(channel) == GPIO.LOW:
	continue
 
while GPIO.input(channel) == GPIO.HIGH:
	continue
 
while j < 40:
	k = 0
	while GPIO.input(channel) == GPIO.LOW:
		continue
	
	while GPIO.input(channel) == GPIO.HIGH:
		k += 1
		if k > 100:
			break
	
	if k < 8:
		data.append(0)
	else:
		data.append(1)
 
	j += 1
 
print("sensor is working.")
print(data)				#輸出初始數據高低電平
 
humidity_bit = data[0:8]		#分組
humidity_point_bit = data[8:16]
temperature_bit = data[16:24]
temperature_point_bit = data[24:32]
check_bit = data[32:40]
 
humidity = 0
humidity_point = 0
temperature = 0
temperature_point = 0
check = 0
 
for i in range(8):
	humidity += humidity_bit[i] * 2 ** (7 - i)				#轉換成十進制數據
	humidity_point += humidity_point_bit[i] * 2 ** (7 - i)
	temperature += temperature_bit[i] * 2 ** (7 - i)
	temperature_point += temperature_point_bit[i] * 2 ** (7 - i)
	check += check_bit[i] * 2 ** (7 - i)
 
tmp = humidity + humidity_point + temperature + temperature_point		#十進制的數據相加
 
if check == tmp:								#數據校驗,相等則輸出
	print ("temperature : ", temperature, ", humidity : " , humidity)
else:										#錯誤輸出錯誤信息,和校驗數據
	print ("wrong")
	print ("temperature : ", temperature, ", humidity : " , humidity, " check : ", check, " tmp : ", tmp)
 
GPIO.cleanup()	

執行之後也可以得到傳感器結果

pi@xiaoyupi:~/RaspberryPiScript $ python3 DHT11.py 
sensor is working.
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1]
temperature :  25 , humidity :  16

使用0.96寸oled屏展示溫溼度

代碼如下

#!/usr/bin/python
import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import Adafruit_DHT

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import subprocess

# Raspberry Pi pin configuration:
RST = None     # on the PiOLED this pin isnt used
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)

# Initialize library.
disp.begin()

# Clear display.
disp.clear()
disp.display()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height-padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0


# Load default font.
font = ImageFont.load_default()

# Alternatively load a TTF font.  Make sure the .ttf font file is in the same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
# font = ImageFont.truetype('Minecraftia.ttf', 8)

while True:
    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    sensor  = 11 # 傳感器型號
    pin = 22 # 針腳
    
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    if humidity is not None and temperature is not None:
        Temp = 'Temp={0:0.1f}*'.format(temperature)
        H = 'Humidity={0:0.1f}%'.format(humidity)

    now = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
    draw.text((x, top),       str(now),  font=font, fill=255)
    draw.text((x, top+8),     str(Temp), font=font, fill=255)
    draw.text((x, top+16),     str(H), font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.display()
    time.sleep(1)

最終實現效果如圖

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章