Directorio de artículos
1. Introducción
Para familiarizarme con el funcionamiento GPIO de la Raspberry Pi, encontré un pequeño estuche, ocurrieron algunos problemas, que solo se resolvieron recientemente, así que lo grabé.
2. Preparación del hardware
1. Sensor de temperatura y humedad DHT11
Las clavijas DHT11 que se venden en el mercado ahora tienen tres clavijas y cuatro clavijas. Como una clavija está vacía, en realidad se usan de la misma manera. Compré tres clavijas.
2. Raspberry Pi 4B
puerto de extensión:
Cableado de pines: (El cableado actual es arbitrario, solo recuerde que la posición de DATOS y los polos positivo y negativo no están conectados al revés)
- VCC - Pin1
- FECHA - Pin3
- GND - Pin6
Tres, preparación de software
Thonny
Utilice el IDE de Python que viene con el sistema
Cuatro, diseño de programa
1. Utilice Adafruit para leer el sensor de temperatura y humedad DHT11
①, instalación de software
Antes de comenzar, debe actualizar el paquete de software:
sudo apt-get update
sudo apt-get install build-essential python-dev
Obtenga la biblioteca Adafruit de GitHub:
sudo git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
Instale la biblioteca para Python 2 y Python 3:
sudo python setup.py install
sudo python3 setup.py install
②, use el programa de muestra
Programa de muestra
Adafruit proporciona un programa de muestra, ejecute el siguiente comando para probarlo.
cd ~
cd Adafruit_Python_DHT
cd examples
python AdafruitDHT.py 11 2
③, un programa Python personalizado que usa la biblioteca Adafruit
Por supuesto, también puede usar esta biblioteca en sus propios programas de Python para implementar llamadas
import Adafruit_DHT
# Set sensor type : Options are DHT11,DHT22 or AM2302
sensor=Adafruit_DHT.DHT11
# Set GPIO sensor is connected to
gpio=2
# Use read_retry method. This will retry up to 15 times to
# get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
# Reading the DHT11 is very sensitive to timings and occasionally
# the Pi might fail to get a valid reading. So check if readings are valid.
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
④ Un programa de Python personalizado para la visualización cíclica en tiempo real de la temperatura y la humedad.
#!/usr/bin/python
# *-*- coding:utf-8 -*-*
import Adafruit_DHT
class DHT11:
def DHT11_Read(self):
sensor = Adafruit_DHT.DHT11
gpio = 2
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
return humidity,temperature
if __name__ == '__main__':
float humid,temp
dht11 = DHT11()
while True:
humid,temp=dht11.DHT11_Read()
if humid is not None and temp is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temp, humid))
else:
print('Failed to get reading. Try again!')
2. Utilice GPIO para leer el sensor de temperatura y humedad DHT11
import RPi.GPIO as GPIO
import time
channel =2 # 上文提到的GPIO编号
data = []
j = 0
GPIO.setmode(GPIO.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.")
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, "*C, humidity :", humidity, "%")
res='{value:%f}'% temperature
import json
with open('/home/pi/Desktop/data.txt', 'a') as outfile:
json.dump(res, outfile)
outest=open('/home/pi/Desktop/data.txt','a')
outest.write(res)
outest.close
print(res)
else:
print ("wrong")
GPIO.cleanup()
Es lógico que no haya ningún problema, pero los resultados no se pueden mostrar, la temperatura y la humedad se muestran 255, el bit de datos no está a la mano, bienvenidos amigos que estén bien informados para responder.
3. Problemas encontrados
①, Raspberry Pi 4B usando Adafruit_DHT no puede mostrar la temperatura correctamente
Esto se debe a que el controlador Adafruit_DHT descargado no es compatible con el procesador 4b BCM2711, debemos abrirlo manualmente /home/pi/Adafruit_Python_DHT/Adafruit_DHT/platform_detect.py
y agregar el siguiente código en el círculo rojo.
elif match.group(1) == 'BCM2711':
# Pi 4b
return 3
Luego regrese al Adafruit_Python_DHT
directorio, reinstale la biblioteca de funciones del sensor Adafruit Python DHT y ejecute el programa de muestra nuevamente para mostrar la temperatura y humedad correctas.
cd Adafruit_Python_DHT/
sudo python setup.py install