DHT11代码解释

DHT11代码解释

#!/usr/bin/python

import RPi.GPIO as GPIO
import time

channel = 17

while True:
    data = []
    j = 0
    # 采用BCM编号
    GPIO.setmode(GPIO.BCM)

    # 延时一秒
    time.sleep(1)

    # 设置17号引脚为输出状态
    GPIO.setup(channel, GPIO.OUT)

    # 令17号引脚输出低电平
    GPIO.output(channel, GPIO.LOW)

    # 延时20毫秒
    time.sleep(0.02)

    # 令17号引脚输出高电平
    GPIO.output(channel, GPIO.HIGH)

    # 设置17号引脚为输入状态
    GPIO.setup(channel, GPIO.IN)

    # 判断17号引脚是否为低电平,如果是,则循环结束
    while GPIO.input(channel) == GPIO.LOW:
        continue
    # 判断17号引脚是否为高电平,如果是,则循环结束
    while GPIO.input(channel) == GPIO.HIGH:
        continue

    while j < 40:
        k = 0
        # 判断17号引脚是否为低电平,如果是,则循环结束
        while GPIO.input(channel) == GPIO.LOW:
            continue
        # 判断17号引脚是否为高电平,如果是,则循环结束
        while GPIO.input(channel) == GPIO.HIGH:
            # k自增
            k += 1
            # 如果k大于100,则退出循环
            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):
        # 湿度为各个数据位的2的7-i次方倍的总和
        humidity += humidity_bit[i] * 2 ** (7 - i)
        # 湿度点为各个数据位的2的7-i次方倍的总和
        humidity_point += humidity_point_bit[i] * 2 ** (7 - i)
        # 温度为各个数据位的2的7-i次方倍的总和
        temperature += temperature_bit[i] * 2 ** (7 - 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:
        f = file("/var/www/html/th/wth.th","w+")
        li = ['{"temperature":%s,"humidity":%s}' % (temperature, humidity) ]
        f.writelines(li)
        f.close()
    
    time.sleep(10)

    del data[:]
    j = 0
  
    #print "temperature : ", temperature, ", humidity : " , humidity
#else:
    #print "wrong"
    #print "temperature : ", temperature, ", humidity : " , humidity, " check : ", check, " tmp : ", tmp

    GPIO.cleanup()

你可能感兴趣的:(树莓派)