-
The DHT11 is a cheap accessory that includes temperature and humidity sensors, and the code is easy to use. This article describes if you use DHT11 in a Raspberry Pi, the code is python. If you have any questions, please leave a comment below.
- VCC Connection 5V or 3.3V
- Data is connected to the Gpio (I'm picking up the BCM pin 16th, the physical pin is 36)
- GND Connection Gnd
[Codesyntax lang= "Python"]
- [Python]View PlainCopy
- #!/usr/bin/python
- Import Rpi.gpio as GPIO
- Import time
- Channel = #引脚号16
- 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 < :
- K = 0
- While gpio.input (channel) = = GPIO. Low:
- Continue
- While gpio.input (channel) = = GPIO. High:
- K + = 1
- if k > :
- 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: +]
- Temperature_bit = data[:
- Temperature_point_bit = data[: +]
- Check_bit = data[:
- 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: #数据校验, equal output
- print "Temperature:", temperature, ", Humidity:", humidity
- else: #错误输出错误信息, and validate data
- print "wrong"
- print "Temperature:", temperature, ", Humidity:", humidity, "check:", check, "tmp:", TMP /c8>
- Gpio.cleanup () #重置针脚
Execution: sudo chmod 777 program name. PY
Python program name. py
Raspberry Pi Connection DHT11 temperature and humidity sensor (python)