02_温湿度传感器
1. 温湿度传感器连接
2. 软件安装
sudo apt-get update
sudo apt-get install build-essential python-dev
3. 从GitHub获取Adafruit库
sudo git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
4. 给Python2安装该库
sudo python setup.py install
5. 实例程序
cd ~
cd Adafruit_Python_DHT
cd examples
python AdafruitDHT.py 11 17#参数为DHT11和数据引脚所接的树莓派GPIO编号
6. python项目
cd
mkdir project
cd project
vim read_retry.py
#coding=utf-8
import Adafruit_DHT
import datetime
#打印当前时间
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
#Set sensor type:Options are DHT11,DHT22 or AM2302
sensor = Adafruit_DHT.DHT11
#Set GPIO sensor is connected to
gpio=17
# 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!')
7.制作获取温湿度脚本
touch temp_humidity.txt
touch get_temp_humidity.sh
/usr/bin/python2.7 /home/pi/project/read_retry.py >> /home/pi/project/temp_humidity.txt
8. 定时启动温湿度脚本
sudo vim /etc/crontab
0 */2 * * * pi sh /home/pi/project/get_temp_humidity.sh
#参考资料:
1.自启动和定时启动:http://www.php.cn/python-tutorials-376149.html
2.温湿度传感器:http://shumeipai.nxez.com/2018/05/16/dht11-temperature-and-humidity-sensor-raspberry-pi.html