本文整理汇总了Python中DHT22.sensor方法的典型用法代码示例。如果您正苦于以下问题:Python DHT22.sensor方法的具体用法?Python DHT22.sensor怎么用?Python DHT22.sensor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DHT22
的用法示例。
在下文中一共展示了DHT22.sensor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
def main():
sensor_handler = sensor.sensor();
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(filename=os.path.dirname(os.path.realpath(__file__)) + '/dht22.log', level=logging.DEBUG,
format=FORMAT)
logger = logging.getLogger('dht22')
print "DHT22 Sensor:"
readout = None
counter = 0
try:
pi = pigpio.pi()
except ValueError:
print "Failed to connect to PIGPIO (%s)"
logger.error('Failed to connect to PIGPIO (%s)', ValueError);
try:
sensor_data = DHT22.sensor(pi, 17)
except ValueError:
print "Failed to connect to DHT22"
logger.error('Failed to connect to DHT22 (%s)', ValueError);
while (readout == None and counter < 5):
counter += 1
# Get data from sensor
sensor_data.trigger()
time.sleep(0.2)
humidity = sensor_data.humidity()
temperature = sensor_data.temperature()
if humidity != None and temperature != None and humidity >= 0 and humidity <= 100:
readout = [humidity, temperature]
saveSQLite(readout)
sensor_handler.save_value(0, temperature)
sensor_handler.save_value(1, humidity)
print "Humidity: " + str(humidity)
print "Temperature: " + str(temperature)
counter = 10
else:
time.sleep(5)
示例2: __init__
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
def __init__(self, root):
Frame.__init__(self, root)
self.pfr = pifacerelayplus.PiFaceRelayPlus(pifacerelayplus.RELAY)
self.pfr.init_board( { 'value': 0,
'direction': 0,
'pullup': 0},
{ 'value': 0,
'direction': 0, # Makes all pins outputs outputs
'pullup': 0})
root.protocol("WM_DELETE_WINDOW", self.on_closing) # This will create a pop-up to confirm ending the program, and
# if there is confirmation it will call the on_closing method
# to tidy up before closing.
# Bench control, Tab 1, variables
self.lightOnImage = PhotoImage(file="icons/light-bulb.png")
self.fanImage = PhotoImage(file="icons/ac.png")
self.ironImage = PhotoImage(file="icons/iron-soldering.png")
self.gpioONImage = PhotoImage(file="icons/switch.png")
self.gpioOFFImage = PhotoImage(file="icons/switch-2.png")
self.hairdryerImage = PhotoImage(file="icons/hairdryer.png")
# Camera, Tab 2 variables
self.camera = picamera.PiCamera()
self.last_photo = None #declaring without defining.
self.isVideoRecording = FALSE
self.isTakingIntervalPhotos = FALSE
self.intervalStillButtonPressed = FALSE
self.intervalImageCounter = 0
self.photoInterval = 5 # interval in seconds.
self.directory_interval = None
self.file_name_interval = None
self.intervalCamera = PhotoImage(file="icons/multiple-shots.png")
self.videoCamera = PhotoImage(file="icons/video-camera.png")
self.add = PhotoImage(file="icons/add.png")
self.remove = PhotoImage(file="icons/minus.png")
self.stillCamera = PhotoImage(file="icons/photo-camera.png")
# Environment, Tab 3 variables
self.pi = pigpio.pi()
self.sensor = DHT22.sensor(self.pi, DHT_SENSOR_PIN)
self.clock = PhotoImage(file="icons/clock.png")
self.humidity = PhotoImage(file="icons/humidity.png")
self.thermometer = PhotoImage(file="icons/thermometer.png")
self.pack(fill=BOTH,expand=True)
self.root = root
self.root.title(PROGRAM_NAME)
self.initUI()
示例3: main
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
def main():
currTemperature = 0
currHumidity = 0
pi = pigpio.pi()
s = DHT22.sensor(pi, 4)
while True:
s.trigger()
time.sleep(0.2)
if s.temperature() != currTemperature:
pubMsg("babykeeper/temperature", s.temperature())
currTemperature = s.temperature()
if s.humidity() != currHumidity:
pubMsg("babykeeper/humidity", s.humidity())
currHumidity = s.humidity()
time.sleep(1) # Overall INTERVAL second polling.
s.cancel()
pi.stop()
示例4: Main
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
def Main():
currTemperature=0
currHumidity=0
#os.system("sudo pigpio")
#subprocess.call(['sudo','pigpiod'],shell=True)
# Intervals of about 2 seconds or less will eventually hang the DHT22.
#INTERVAL=3
pi = pigpio.pi()
s = DHT22.sensor(pi, 4)
pubIp()
curr=getAddress()
while True:
s.trigger()
time.sleep(0.2)
'''
print("{} {} {}".format(
r, s.humidity(), s.temperature()))
'''
if curr != getAddress():
pub()
curr=getAddress()
pubChangedTemperature()
pubChangedHumidity()
time.sleep(1) # Overall INTERVAL second polling.
s.cancel()
pi.stop()
示例5: open
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
# usr/bin python3
import pigpio
import time
pi = pigpio.pi()
import DHT22
## s = DHT22.sensor(pi, 17) #works with out led blinking
s = DHT22.sensor(pi, 17, 27) # works and blinks led
s.trigger()
fo = open("/home/pi/temp_log.txt", "w")
count = 0
while (count < 30000):
time.sleep(60)
s.trigger()
localtime = time.asctime( time.localtime(time.time()) )
#print("Time : {0}".format(localtime))
fo.writelines("Time : {0}".format(localtime));
fo.writelines(' Humidity : {0:3.2f}'.format(s.humidity() / 1.));
#print('Humidity : {:3.2f}'.format(s.humidity() / 1.))
#print('Temp : {:3.2f}'.format((s.temperature() * 1.8) +32))
fo.writelines(' Temp : {0:3.2f}\n'.format((s.temperature() * 1.8) +32));
count = count + 1
fo.close()
s.cancel()
pi.stop()
示例6: readDHT22
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
CONTINUOUS_HIGH_RES_MODE_2 = 0x11
ONE_TIME_HIGH_RES_MODE_1 = 0x20
ONE_TIME_HIGH_RES_MODE_2 = 0x21
ONE_TIME_LOW_RES_MODE = 0x23
bus = smbus.SMBus(1)
relay_pin1 = 23
relay_pin2 = 24
relay_pin3 = 25
temp_pin = 22
motion_pin = 18
# Initiate GPIO for pigpio
pi = pigpio.pi()
# Setup the sensor
dht22 = DHT22.sensor(pi,temp_pin) # use the actual GPIO pin name
dht22.trigger()
# We want our sleep time to be above 3 seconds.
sleepTime = 3
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay_pin1,GPIO.OUT)
GPIO.setup(relay_pin2,GPIO.OUT)
GPIO.setup(relay_pin3,GPIO.OUT)
GPIO.setup(motion_pin, GPIO.IN)
presence = GPIO.input(motion_pin)
def readDHT22():
# Get a new reading
示例7: readTempRaw
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
sleepTime = 900
baseDir = '/sys/bus/w1/devices/'
#deviceFolder = glob.glob(baseDir + '28-000006c8044b')[0]
deviceFolderOut = glob.glob(baseDir + '28-000006c8044b')[0]
deviceFolderIn2 = glob.glob(baseDir + '28-041591ae04ff')[0]
deviceFolderIn3 = glob.glob(baseDir + '28-01159110bcff')[0]
deviceFileOut = deviceFolderOut + '/w1_slave'
deviceFileIn2 = deviceFolderIn2 + '/w1_slave'
deviceFileIn3 = deviceFolderIn3 + '/w1_slave'
pi = pigpio.pi()
dht22 = DHT22.sensor(pi,4,17)
dht22.trigger()
json_key = json.load(open('/home/pi/zend_dht/credentials.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gspCred = False
worksheet = False
dbconn = sqlite3.connect('/home/pi/dht.db')
dbcurs = dbconn.cursor()
print("Meteo station v1.3")
def readTempRaw(deviceFile):
f = open(deviceFile, 'r')
lines = f.readlines()
示例8: AQI
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
s = air_quality.sensor(pi, 7) # set the GPIO pin number
time.sleep(30) # Use 30s for a properly calibrated reading.
g, r, c = s.read() # get the gpio, ratio and concentration in particles / 0.01 ft3
concentration_ugm3 = s.pcs_to_ugm3(c) # convert to SI units
aqi = s.ugm3_to_aqi(concentration_ugm3) # convert SI units to US AQI (instantaneous only)
return aqi
if __name__ == "__main__":
'''
Main program - reads all sensors and sends readings to thingspeak
'''
pi = pigpio.pi()
# Humidity and temp from DHT22 (outisde)
s = DHT22.sensor(pi, PIN_DHT22, LED=None, power=8)
s.trigger()
time.sleep(0.2)
humidity = s.humidity()
temp1 = s.temperature()
# Humidity and temp from DHT22 (inside)
#si = DHT22.sensor(pi, PIN_DHT22i, LED=None, power=8)
#si.trigger()
#time.sleep(0.2)
#humidityi = si.humidity()
# temp and pressure from BMP085
temp2 = BMP085sensor.read_temperature()
pressure = BMP085sensor.read_pressure()
示例9: print
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
if __name__ == "__main__":
import time
import pigpio
import DHT22
# Intervals of about 2 seconds or less will eventually hang the DHT22.
INTERVAL=3
pi = pigpio.pi()
# s = DHT22.sensor(pi, 22, LED=16, power=8)
s = DHT22.sensor(pi, 17)
r = 0
next_reading = time.time()
while True:
r += 1
s.trigger()
time.sleep(0.2)
print("{} humidity: {} temp(C): {} temp(F): {} {:3.2f} {} {} {} {}".format(
r, s.humidity(), s.temperature(), s.temperature()*9/5+32, s.staleness(),
示例10: readDHT22
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
ch0 = data[1] * 256 + data[0]
ch1 = data1[1] * 256 + data1[0]
"""
DHT22 code
"""
import pigpio
import DHT22
import time
##import datetime
##from time import sleep
##import RPi.GPIO as GPIO
## must run sudo pigpiod from cmd prompt prior to running this script after
## every restart of PI.
pi = pigpio.pi() ## Initiate GPIO for pigpio.
dht22 = DHT22.sensor(pi, 17) ## use the actual GPIO pin name/number
dht22.trigger() ## forces a reading. first reading is just junk.
sleepTime = 3 ## must sleep at least 3 second to stop sensor hangs.
def readDHT22():
dht22.trigger()
humidity = " %.2f" % (dht22.humidity())
temp = " %.2f" % (dht22.temperature())
return (humidity, temp)
def Temp_Tol():
temperature = int(temperature)
if temperature + "%" > int(27.00):
print("\n\n Temperature too High")
else:
print(" ")
示例11: __init__
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
def __init__(self, pi, gpio, LED=None, power=None):
"""
Instantiate with the Pi and gpio to which the DHT22 output
pin is connected.
Optionally a LED may be specified. This will be blinked for
each successful reading.
Optionally a gpio used to power the sensor may be specified.
This gpio will be set high to power the sensor. If the sensor
locks it will be power cycled to restart the readings.
Taking readings more often than about once every two seconds will
eventually cause the DHT22 to hang. A 3 second interval seems OK.
"""
self.pi = pi
self.gpio = gpio
self.LED = LED
self.power = power
if power is not None:
pi.write(power, 1) # Switch sensor on.
time.sleep(2)
self.powered = True
self.cb = None
atexit.register(self.cancel)
self.bad_CS = 0 # Bad checksum count.
self.bad_SM = 0 # Short message count.
self.bad_MM = 0 # Missing message count.
self.bad_SR = 0 # Sensor reset count.
# Power cycle if timeout > MAX_TIMEOUTS.
self.no_response = 0
self.MAX_NO_RESPONSE = 2
self.rhum = -999
self.temp = -999
self.tov = None
self.high_tick = 0
self.bit = 40
print(("test"))
pi.set_pull_up_down(gpio, pigpio.PUD_OFF)
pi.set_watchdog(gpio, 0) # Kill any watchdogs.
self.cb = pi.callback(gpio, pigpio.EITHER_EDGE, self._cb)
def _cb(self, gpio, level, tick):
"""
Accumulate the 40 data bits. Format into 5 bytes, humidity high,
humidity low, temperature high, temperature low, checksum.
"""
diff = pigpio.tickDiff(self.high_tick, tick)
if level == 0:
# Edge length determines if bit is 1 or 0.
if diff >= 50:
val = 1
if diff >= 200: # Bad bit?
self.CS = 256 # Force bad checksum.
else:
val = 0
if self.bit >= 40: # Message complete.
self.bit = 40
elif self.bit >= 32: # In checksum byte.
self.CS = (self.CS << 1) + val
if self.bit == 39:
# 40th bit received.
self.pi.set_watchdog(self.gpio, 0)
self.no_response = 0
total = self.hH + self.hL + self.tH + self.tL
if (total & 255) == self.CS: # Is checksum ok?
self.rhum = ((self.hH << 8) + self.hL) * 0.1
if self.tH & 128: # Negative temperature.
mult = -0.1
self.tH = self.tH & 127
else:
mult = 0.1
self.temp = ((self.tH << 8) + self.tL) * mult
self.tov = time.time()
#.........这里部分代码省略.........
示例12: strftime
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
observation = owm.weather_at_place('Ghaziabad,India')
w = observation.get_weather()
h = w.get_humidity()
t = w.get_temperature('celsius')
data = {}
data['et'] = t['temp']
data['eh'] = h
data['etmin'] = t['temp_min']
data['etmax'] = t['temp_max']
### get weather data from sensor ###
pi = pigpio.pi()
s = DHT22.sensor(pi, 4, 27)
s.trigger()
time.sleep(0.2)
data['it'] = s.temperature()
data['ih'] = s.humidity()
s.cancel()
pi.stop()
### index data ###
data['dt'] = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
json_data = json.dumps(data)
print("{}".format(json_data))
示例13: sensor_settings
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
#---------------------------------------------------------------------------
# SET UP SENSOR VARIABLES
#---------------------------------------------------------------------------
sensor_value = {x: 'U' for x in s.SENSOR_SET}
sensor_settings = collections.namedtuple('sensor_settings',
'enable ref unit min max type')
sensor = {k: sensor_settings(*s.SENSOR_SET[k]) for k in s.SENSOR_SET}
#-------------------------------------------------------------------
# Get inside temperature and humidity
#-------------------------------------------------------------------
if sensor['inside_temp'].enable or sensor['inside_hum'].enable:
try:
DHT22_sensor = DHT22.sensor(pi, sensor['inside_temp'].ref)
DHT22_sensor.trigger()
time.sleep(0.2) #Do not over poll DHT22
DHT22_sensor.cancel()
if sensor['inside_temp'].enable:
sensor_value['inside_temp'] = DHT22_sensor.temperature()
if sensor['inside_hum'].enable:
sensor_value['inside_hum'] = DHT22_sensor.humidity()
logger.info('Reading value from DHT22 sensor... OK')
except ValueError:
logger.warning('Failed to read DHT22 ({value_error})'.format(
value_error=ValueError))
示例14: __init__
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
def __init__(self, root):
Frame.__init__(self, root)
# The following works with the Piface Relay+
'''
self.pfr = pifacerelayplus.PiFaceRelayPlus(pifacerelayplus.RELAY)
self.pfr.init_board( { 'value': 0,
'direction': 0,
'pullup': 0},
{ 'value': 0,
'direction': 0, # Makes all pins outputs outputs
'pullup': 0})
'''
root.protocol("WM_DELETE_WINDOW", self.on_closing) # This will create a pop-up to confirm ending the program, and
# if there is confirmation it will call the on_closing method
# to tidy up before closing.
# Bench control, Tab 1, variables
self.lightOnImage = PhotoImage(file="icons/light-bulb.png")
self.fanImage = PhotoImage(file="icons/ac.png")
self.ironImage = PhotoImage(file="icons/iron-soldering.png")
self.gpioONImage = PhotoImage(file="icons/switch.png")
self.gpioOFFImage = PhotoImage(file="icons/switch-2.png")
self.hairdryerImage = PhotoImage(file="icons/hairdryer.png")
# Camera, Tab 2 variables
# Don't enable the camera if an actual camera is not connected to the RPi
self.camera = picamera.PiCamera()
self.last_photo = None #declaring without defining.
self.isVideoRecording = FALSE
self.isTakingIntervalPhotos = FALSE
self.intervalStillButtonPressed = FALSE
self.intervalImageCounter = 0
self.photoInterval = 5 # interval in seconds.
self.directory_interval = None
self.file_name_interval = None
self.intervalCamera = PhotoImage(file="icons/multiple-shots.png")
self.videoCamera = PhotoImage(file="icons/video-camera.png")
self.add = PhotoImage(file="icons/add.png")
self.remove = PhotoImage(file="icons/minus.png")
self.stillCamera = PhotoImage(file="icons/photo-camera.png")
# Environment, Tab 3 variables
self.pi = pigpio.pi()
# Don't setup the DHT sensor unless a sensor is actually connected
self.sensor = DHT22.sensor(self.pi, DHT_SENSOR_PIN)
self.clock = PhotoImage(file="icons/clock.png")
self.humidity = PhotoImage(file="icons/humidity.png")
self.thermometer = PhotoImage(file="icons/thermometer.png")
# Setup relay GPIOS
self.fan_gpio = 22 # On the relay board
self.lights_gpio = 6 # On the relay board
self.solder_iron_gpio = 10 # External relay
self.hot_air_gpio = 9 # External relay
self.pi.set_mode(self.hot_air_gpio,pigpio.OUTPUT) # Make output
self.pi.set_mode(self.solder_iron_gpio,pigpio.OUTPUT) # Make output
self.pi.set_mode(self.fan_gpio,pigpio.OUTPUT) # Make output
self.pi.set_mode(self.lights_gpio,pigpio.OUTPUT) # Make output
self.pi.write(self.hot_air_gpio,0) # Set to LOW
self.pi.write(self.solder_iron_gpio,0) # Set to LOW
self.pi.write(self.fan_gpio,0) # Set to LOW
self.pi.write(self.lights_gpio,0) # Set to LOW
self.pack(fill=BOTH,expand=True)
self.root = root
self.root.title(PROGRAM_NAME)
self.initUI()
示例15: dict
# 需要导入模块: import DHT22 [as 别名]
# 或者: from DHT22 import sensor [as 别名]
argNames = ['filename', 'temperature']
args = dict(zip(argNames, sys.argv))
# setting some default values, Pin # using BGM
sensorPin = 19
sensorVoltagePin = 26
targetOutputPin = 12 # this is the pin giving signal to relay -> fan motor
sleepTime = 3
targetTemperature = int(args['temperature']) # getting the input from argv
pi = pigpio.pi()
# turn on the sensor
pi.set_mode(sensorVoltagePin, pigpio.OUTPUT)
pi.write(sensorVoltagePin, True)
# setup the DHT22 sensor pin
dht22 = DHT22.sensor(pi, sensorPin)
# setup the relay -> fan motor output pin
pi.set_mode(targetOutputPin, pigpio.OUTPUT)
# defined how to read the DHT22
def readDHT22():
dht22.trigger()
humidity = '%.2f' % (dht22.humidity())
temp = '%.2f' % (dht22.temperature())
return (float(humidity), float(temp))
# the core program run
try:
print("[Please use Ctrl + C to termate the program]\n")
print("Program Start...")
print("When the temperature is HIGHER then " + str(targetTemperature) + ". The relay -> fan motor will turn on!\n")