本文整理汇总了Python中DHT22类的典型用法代码示例。如果您正苦于以下问题:Python DHT22类的具体用法?Python DHT22怎么用?Python DHT22使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DHT22类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main_client
def main_client(addr):
nic = network.WIZNET5K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4)
nic.ifconfig((SENSOR_IP, SENSOR_MASK, SENSOR_GATEWAY, SENSOR_DNS))
# print(nic.ifconfig())
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
count = 0
try:
s.connect(addr)
except:
pass
data = {
'serial_no':'1234567890',
'ip':SENSOR_IP,
'op':gOperator['OP_REGISTER'],
'type':gSensorType['TEMPERATURE']
}
DHT22.init()
while True:
pyb.delay(100)
hum, tem = measure()
print('%d hum:%f, tem:%f' % (count,hum, tem))
data['value'] = {'hum':hum, 'tem':tem}
count += 1
try:
send(s, 'post', '/test_pymagic', data)
print(s.recv(4096))
except:
pass
pyb.delay(1000)
示例2: measure
def measure(led, lcd):
try:
(hum, tem) = DHT22.measure()
if ((hum == 0) and (tem == 0)) or (hum > 100):
raise ValueError('Invalid data received from sensor')
lcd.write('\nHumidity: %s%%\n Temp: %sC\n\n' % (hum, tem))
led.off()
except Exception as e:
lcd.write(str(e) + '\n')
led.on()
示例3: main
def main():
##-------------------------------------------------------------------------
## Parse Command Line Arguments
##-------------------------------------------------------------------------
## create a parser object for understanding command-line arguments
parser = argparse.ArgumentParser(
description="Program description.")
## add flags
parser.add_argument("-v", "--verbose",
action="store_true", dest="verbose",
default=False, help="Be verbose! (default = False)")
## add arguments
parser.add_argument("--input",
type=str, dest="input",
help="The input.")
args = parser.parse_args()
##-------------------------------------------------------------------------
## Create logger object
##-------------------------------------------------------------------------
logger = logging.getLogger('MyLogger')
logger.setLevel(logging.DEBUG)
## Set up console output
LogConsoleHandler = logging.StreamHandler()
if args.verbose:
LogConsoleHandler.setLevel(logging.DEBUG)
else:
LogConsoleHandler.setLevel(logging.INFO)
LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s')
LogConsoleHandler.setFormatter(LogFormat)
logger.addHandler(LogConsoleHandler)
## Set up file output
# LogFileName = None
# LogFileHandler = logging.FileHandler(LogFileName)
# LogFileHandler.setLevel(logging.DEBUG)
# LogFileHandler.setFormatter(LogFormat)
# logger.addHandler(LogFileHandler)
# os.system('modprobe w1-gpio')
# os.system('modprobe w1-therm')
##-------------------------------------------------------------------------
## Read DS18B20 Temperature Sensors
##-------------------------------------------------------------------------
temps = DS18B20.read()
for temp in temps:
logger.info('Temperature (DS18B20) = {:.1f} F'.format(temp))
##-------------------------------------------------------------------------
## Read DHT22 Temperature and Humidity Sensor
##-------------------------------------------------------------------------
temp_DHT, humidity = DHT22.read()
logger.info('Temperature (DHT22) = {:.1f} F'.format(temp_DHT))
logger.info('Humidity (DHT22) = {:.0f} %'.format(humidity))
示例4: main
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)
示例5: __init__
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()
示例6: main
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()
示例7: Main
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()
示例8: open
# 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()
示例9: readDHT22
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
示例10: sensor
logFileName = ("/home/pi/lake_status/GetConditions.log")
logging.basicConfig(filename=logFileName, level=loglevel,
format='%(asctime)s %(levelname)s %(message)s')
logging.debug("logger started")
start_time = time.time()
parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id$')
parser.add_option ('-p', '--pythonanywhere', action='store_true', help='sends data to pythonanywhere database')
parser.add_option ('-c', '--carriots', action='store_true', help='sends data to carriots')
(options, args) = parser.parse_args()
#get the data from the sensor (pigpiod must be running with root permission)
logging.debug('trying to get data from dht22')
try:
pi = pigpio.pi()
dht22 = DHT22.sensor(pi, 4, None, 24)
#trigger the event, gather the data
dht22.trigger()
#check to see if data is relevant, first reading is generally bad, -999 is not right...
count = 0
while dht22.temperature() > 150 or dht22.temperature() < -20:
count = count + 1
#wait 3 seconds and try again.
logging.debug('bad data from sensor, count : %10o' % count)
time.sleep(3)
dht22.trigger()
#error occurred, twenty queries to sensor (1min) and no data.
if count > 20:
logging.error("Sensor didn't return any data. Exiting.")
sys.exit(2)
示例11: readDHT22
def readDHT22():
DHT22.triger()
temperature = '%.2f' % (DHT22.temperature())
return temperature
示例12:
def getHumidity:
HT22.triger()
humidity = '%.2f' % (DHT22.hymidity())
return humidity
示例13: __init__
def __init__(self, *a, **kw):
DeviceType.__init__(self, *a, **kw)
import DHT22
self.sens = DHT22.sensor(self.pi, self.pinNumber)
self.recentLowTemp = (0, None) # time, temp
self.recentPeriodSec = 30
示例14: print
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(),
示例15: dict
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")