def read_humidity(): t, h = dhtreader.read(22, 17) if t and h: return str(round(t, 3)) + ";" + str(round(h,3)) else: time.sleep(5) t, h = dhtreader.read("22", "17") if t and h: return str(t) + ";" + str(h) else: return "ERR;ERR"
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff): global oldtemp global oldhumid for num in range(retries): try: t, h = dhtreader.read(dev_type, dhtpin) except: if ((num + 1) < retries): logging.warning('Exception detected! We will retry. Loop number: %d', num) time.sleep(timeout) else: logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.') else: if t and h: logging.debug('The temperature and humidity have been read as {0} and {1}'.format(t, h)) if (oldtemp != "NULL") and ((t - oldtemp < tempdiff) or (oldtemp - t < tempdiff)) and ((h - oldhumid < humiddiff) or (oldhumid - h < humiddiff)): logging.debug('Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s', oldtemp) logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid) if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid): logging.debug('Temperature is less than {0} and greater than {1}, humidity is less than {2} and greater than {3}'.format(maxtemp,mintemp,maxhumid,minhumid)) updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout) oldtemp=t oldhumid=h break else: logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h)) else: logging.warning('Failed to read from sensor, maybe try again?') return 0
def read_temp_and_hum(): dhtreader.init() temp_and_hum = dhtreader.read(11, 4) if temp_and_hum: return temp_and_hum else: print "[Error:] Failed to read from sensor, maybe try again?"
def recedata(): t, h = dhtreader.read(22, 4) fmt = "%Y-%m-%d %H:%M" # Current time in UTC now_utc = datetime.now(timezone('UTC')) # Convert to US/Pacific time zone now_aus = now_utc.astimezone(timezone('Australia/Brisbane')) print now_aus.strftime(fmt) db = MySQLdb.connect("localhost", "root", "raspberry", "temp_hum") cursor = db.cursor() print("Connected to the DataBase") print("Temp: {0} *C, Hum: {1} %".format(t, h)) sql = "INSERT INTO TEMP(TIME, \ TEMP, HUM) \ VALUES ('%s', '%f','%f' )" % \ (now_aus.strftime(fmt), t, h) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() db.close() return (t, h)
def recedata(): t,h = dhtreader.read(22,4) fmt = "%Y-%m-%d %H:%M" # Current time in UTC now_utc = datetime.now(timezone('UTC')) # Convert to US/Pacific time zone now_aus = now_utc.astimezone(timezone('Australia/Brisbane')) print now_aus.strftime(fmt) db = MySQLdb.connect("localhost","root","raspberry","temp_hum" ) cursor = db.cursor() print("Connected to the DataBase") print("Temp: {0} *C, Hum: {1} %".format(t,h)) sql = "INSERT INTO TEMP(TIME, \ TEMP, HUM) \ VALUES ('%s', '%f','%f' )" % \ (now_aus.strftime(fmt), t, h) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() db.close() return (t,h)
def _read(self): try: value = dhtreader.read(self.type, self.settings['pin']) if value: return {"temperature": value[0], "humidity": value[1]} except TimeoutError: return None return None
def readDht11(self): res = None while res is None: res = dhtreader.read(self.type, self.port) return res
def reportTemperature(): try: t, h = dhtreader.read(11, dht11Pin) print("Temp = {0} *C".format(t)) client.publish("/" + thingID + "/" + dhtItemKey, t) except: print "Unexpected error:", sys.exc_info()[0] threading.Timer(5.0, reportTemperature).start()
def get_Temp(): print "====================DHT22=============================" data = dhtreader.read(type, pin) if data != None: feuchtigkeit = data[1] feuchtigkeit1 = round(feuchtigkeit, 3) Temperatur = data[0] Temperatur1 = round(Temperatur, 3) print(feuchtigkeit1) print(Temperatur1) print(data)
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff): global oldtemp global oldhumid startTime = datetime.now() logging.debug("This round of results started at {0}".format(startTime)) for num in range(retries): try: t, h = dhtreader.read(dev_type, dhtpin) except: if (num + 1) < retries: logging.warning("Exception detected! We will retry. Loop number: %d", num) time.sleep(timeout) else: logging.error("Exception detected - we are out of retries. Skipping the measurement in this cycle.") else: if t and h: logging.debug("Temperature and humidity read as {0} and {1}".format(t, h)) logging.debug("Temperature and Humidity differences allowed: {0} and {1}".format(tempdiff, humiddiff)) if ( (oldtemp != "NULL") and ((t - oldtemp < tempdiff) or (oldtemp - t < tempdiff)) and ((h - oldhumid < humiddiff) or (oldhumid - h < humiddiff)) ): logging.debug( "Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s", oldtemp, ) logging.debug( "Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s", oldhumid, ) if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid): logging.debug( "Temperature is less than {0} and greater than {1}, humidity is less than {2} and greater than {3}".format( maxtemp, mintemp, maxhumid, minhumid ) ) updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout) oldtemp = t oldhumid = h break else: logging.error( "Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.".format( t, h ) ) else: logging.warning("Failed to read from sensor, maybe try again?") endTime = datetime.now() logging.debug("This round of results ended at {0}".format(endTime)) duration = endTime - startTime logging.debug("This round of results took {0} to complete".format(duration)) return duration
def read_dht(): # Run the DHT program to get the humidity and temperature readings! temp = None humidity = None dhtoutput = dhtreader.read(dht_type, dht_pin) if dhtoutput != None: temp = dhtoutput[0] humidity = dhtoutput[1] return temp, humidity
def temperature(self): """Return (temparature, humidity)""" try: t, h = dhtreader.read(self.dhttype,self.dhtpin) t = math.floor(t * 100) / 100 #round to 2 decimal places h = math.floor(h * 100) / 100 return (t, h) except TypeError: d,t,s = self.timestamp() print '\n', d, '\t', t, '\terror reading temperature/humidity\n' return ('', '') except: raise
def read(pin): i = 0 while i<10: try: dhtreader.init() t, h = dhtreader.read(22, pin) if t and h: t = float("{0:.2f}".format(t)) h = float("{0:.2f}".format(h)) return t, h, True finally: i = i + 1 return False
def get_humidity(self): humidity = 0.0 humidityData = [] while len(humidityData) < 5: try: humidity = float(dhtreader.read(11, 17)[1]) humidityData.append(humidity) except: pass time.sleep(0.5) return sum(humidityData)/5.0
def read_sensors(): readings = {} # Iterate through the devices. for name, device in settings['dht_devices'].iteritems(): # Read the temperature and humidity from the device. tc, h = dhtreader.read(sensor_types[device['type']], device['pin']) # Convert celsius to fahrenheit. tf = tc * 9.0 / 5.0 + 32.0 # Add the measurements to the readings array. readings[name] = {'H': h, 'C': tc, 'F': tf} # Return the list of devices and their readings. return readings
def read_sensor(type, pin): # Read the temperature and humidity from the device. tc, h = dhtreader.read(sensor_types[type], int(pin)) # Convert celsius to fahrenheit. tf = tc * 9.0 / 5.0 + 32.0 # Round all measurements to the precision defined in settings. tc = round(tc, settings['precision']) tf = round(tf, settings['precision']) h = round(h, settings['precision']) # Format the reading data. reading = {'H': h, 'C': tc, 'F': tf} # Return the reading. return reading
def getVal(self): tm = dhtreader.lastDataTime if (time.time() - tm) < 2: t, h = dhtreader.lastData else: try: t, h = dhtreader.read(22, self.pinNum) except Exception: t, h = dhtreader.lastData dhtreader.lastData = (t, h) dhtreader.lastDataTime = time.time() if self.valType == "Temperature": temp = t if self.valUnit == "Fahrenheit": temp = temp * 1.8 + 32 return temp elif self.valType == "Relative_Humidity": return h
def read_sensor(type, pin): # Read the temperature and humidity from the device. tc, h = dhtreader.read(sensor_types[type], int(pin)) # Convert celsius to fahrenheit. tf = tc * 9.0 / 5.0 + 32.0 # Round all measurements to the precision defined in settings. tc = round(tc, settings["precision"]) tf = round(tf, settings["precision"]) h = round(h, settings["precision"]) # Format the reading data. reading = {"H": h, "C": tc, "F": tf} # Return the reading. return reading
def getVal(self): tm = dhtreader.lastDataTime if (time.time()-tm)<2: t, h = dhtreader.lastData else: tim = time.time() try: t, h = dhtreader.read(22,self.pinNum) except Exception: t, h = dhtreader.lastData dhtreader.lastData = (t,h) dhtreader.lastDataTime=tim if self.valName == "Temperature": temp = t if self.valUnit == "Fahrenheit": temp = temp * 1.8 + 32 return temp elif self.valName == "Relative_Humidity": return h
def getTemp(): check = False while check == False: data = dhtreader.read(type, pin) if data != None: feuchtigkeit = data[1] feuchtigkeit1 = round(feuchtigkeit, 3) Temperatur = data[0] Temperatur1 = round(Temperatur, 3) #print feuchtigkeit1 #print Temperatur1 check = True return feuchtigkeit1, Temperatur1 else: check = False
def getData(pin): # if len(sys.argv) != 3: # print("usage: {0} [11|22|2302] GPIOpin#".format(sys.argv[0])) # print("example: {0} 2302 Read from an AM2302 connected to GPIO #4".format(sys.argv[0])) # sys.exit(2) # dev_type = None # if sys.argv[1] == "11": # dev_type = DHT11 # elif sys.argv[1] == "22": # dev_type = DHT22 # elif sys.argv[1] == "2302": # dev_type = AM2302 # else: # print("invalid type, only 11, 22 and 2302 are supported for now!") # sys.exit(3) dev_type = DHT11 dhtpin = pin return dhtreader.read(dev_type, dhtpin)
def run (self): print colored("Starting temperature and humidity sensor", 'green') while True: temphumid = dhtreader.read(tempType, tempPin) if temphumid is not None: t, h = temphumid # sys.stdout.write("\r[DHT] Temp: {0} *C, Hum: {1} %\r".format(t, h) # sys.stdout.flush() print colored("[DHT] Temp: {0} *C, Hum: {1} %\r".format(t, h), 'green') dhtfile_t = open('/var/www/crest/dhtfile_t.txt', 'w') dhtfile_t.write(str(t) + "*C") dhtfile_t.close() dhtfile_h = open('/var/www/crest/dhtfile_h.txt', 'w') dhtfile_h.write(str(h) + "%") dhtfile_h.close() if t > 50: print colored("TEMPERATURE went above 50*C - help!\r", 'red') if h > 50: print colored("HUMIDITY went above 50 - it's gonna rain!\r", 'red') else: time.sleep(3)
def provide_temperature_and_humidity(): dhtreader.init() return dhtreader.read(dht_measurer_type, dht_measurer_pin)
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys import dhtreader import time dhtreader.init() Attempts = 0 while True: try: t, h = dhtreader.read(22, 23) break except TypeError: print("Failed to read from sensor on GPIO 23, trying again...") time.sleep(3) Attempts = Attempts + 1 if Attempts >= 5: break if t and h: print("AM2032 on GPIO 23: Temp = {0}*C, Hum = {1}%".format(t, h)) else: print("Failed to read from sensor.") Attempts = 0 while True: try: t, h = dhtreader.read(22, 24) break except TypeError:
def main(): logging_level = loglvl_setup() logging.debug("Starting up....") if not 'SUDO_UID' in os.environ.keys(): logging.critical("This program requires super user privs.") logging.critical( "Sorry, it's because the DHTreader library accesses /dev/mem for" \ " real-time GPIO toggling to communicate with the DHT11/22") return 0 # config.ini should be in the same location as the script # get script path with some os.path hackery # check if config.ini does exist if not (os.path.exists(INI_FILE)): logging.critical("ERROR: config.ini does not exist...exiting") return 0 current_path = os.path.dirname(os.path.realpath(__file__)) config = ConfigRead(os.path.join(current_path, INI_FILE)) logging.debug("Setup Threads & Queues") upload_queue = Queue.Queue(maxsize=0) uploadThread = BackgroundUpload(upload_queue, config, logging, "UploadThread") uploadThread.start() # Open serial port for use by the XBee ser = serial.Serial(config.XbeePort, config.XbeeBaud) # The AlertMe object handles both bringing the ZB link up with the clamp # as well as pushing recieved data to teh upload queue zigbee = AlertMe(ser, upload_queue, logging) q1 = QueueObject() q1.type = QueueObject.Temp q2 = QueueObject() q2.type = QueueObject.RH # Initialise the DHTReader C Library dhtreader.init() while True: try: t, h = dhtreader.read(config.DHTtype, config.DHTpin) logging.debug("temp %d. RH %d" % (t, h)) if t and h: timestamp = datetime.datetime.utcnow() #add temperature to upload queue q1.data = format(t, '.2f') q1.timestamp = timestamp #add RH to upload queue q2.data = format(h, '.2f') q2.timestamp = timestamp #push both objects to upload queue upload_queue.put(q1) upload_queue.put(q2) else: logging.warning("Failed to read from sensor, maybe try again?") except KeyboardInterrupt: zigbee.close() logging.info("Wait until all data is uploaded") upload_queue.join() break except TypeError: #This seems to happen a fair bit with the DHT22 logging.info('NoneType return from dhtreader()') #try re-initing.... dhtreader.init() # Sleep for 30 seconds #(the RPi Python version does not send a SIGINT when in sleep) # So sleep in parts... for i in range(30): time.sleep(1)
sys.exit(2) dev_type = None if sys.argv[1] == "11": dev_type = DHT11 elif sys.argv[1] == "22": dev_type = DHT22 elif sys.argv[1] == "2302": dev_type = AM2302 else: print("invalid type, only 11, 22 and 2302 are supported for now!") sys.exit(3) dhtpin = int(sys.argv[2]) if dhtpin <= 0: print("invalid GPIO pin#") sys.exit(3) print("using pin #{0}".format(dhtpin)) while True: result = dhtreader.read(dev_type, dhtpin) if result: t, h = result if t and h: print("Temp = {0} *C, Hum = {1} %".format(t, h)) else: print("Failed to read from sensor, maybe try again?") time.sleep(1)
password='******', security_token='xxxxxxxxxxxxxxxxx', sandbox=False) testReading = SFType('testReadingPy__c', session_id=session_id, sf_instance='na17.salesforce.com', sf_version='32.0', proxies=None) def RCtime (RCpin): reading = 0 GPIO.setup(RCpin, GPIO.OUT) GPIO.output(RCpin, GPIO.LOW) time.sleep(0.1) GPIO.setup(RCpin, GPIO.IN) while (GPIO.input(RCpin) == GPIO.LOW): reading += 1 return 100-(reading/10) while True: dhtreader.init() output = dhtreader.read(type,pin) lightval = str(RCtime(17)) if output!=None: output=str(output) output=output[1:-1] output=output.translate(None, ',') output = output + ' ' + lightval a,b,c = output.split(" ") print a+b+c testReading.create({'Temperature_Reading__c' : a, 'Humidity_Reading__c' : b, 'Light_Reading__c' : c, 'Hidden_Sensor_Index__c' : 'xxxxxxxxxx'}) time.sleep(1800)
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys import dhtreader dhtreader.init() print dhtreader.read(11, 4) t, h = dhtreader.read(11, 4) print t print h
def get_data(dht, pin): data = str(dhtreader.read(dht, pin)) return eval(data)
def collectData(numberOfTimes): print "Begin Recording Data" sonarMeasurements = [] temperatureMeasurements = [] humidityMeasurements = [] pressureMeasurements = [] # LEDs gpio.output(rLEDPin, 1) #gpio.output(gLEDPin, 0) x = 0 while True: gpio.output(yLEDPin, 1) print "================================================================" print "Measurement number: "+str(x+1) # Start Sonar Measurement gpio.output(sTrig, 1) time.sleep(0.00001) gpio.output(sTrig, 0) timeout = time.time() + timeoutTime didTimeout = False # Wait for the echo while gpio.input(sEcho) == 0: if time.time() > timeout: print "Sonar sensor has timed out... Skip this round." didTimeout = True break #pass start = time.time() if didTimeout == False: timeout = time.time() + timeoutTime # Once we get the echo while gpio.input(sEcho) == 1: if time.time() > timeout: print "Sonar sensor has timed out... Skip this round." didTimeout = True break #pass stop = time.time() if didTimeout == False: # Assuming sound travels at 340m/s # Remove a zero for distance in centimetres distance = (stop-start)*170000 # Finish Sonar Measurement print "Got Sonar: "+str(distance)+"mm." try: # Start Fetching DHT22 Measurements readings = dhtreader.read(dhtType, dhtPin) temperature = readings[0] humidity = readings[1] # Finish DHT22 Measurements #print "DHT 22 Done" bmpTemp = bmp.read_temperature() bmpPressure = bmp.read_pressure() #print readings print "Got DHT22: Temperature = "+str(temperature)+" Celsius. Humidity = "+str(humidity)+"%." print 'Got BMP180(085): Temperature = '+str(bmpTemp)+' Celsius. Pressure = '+str(bmpPressure)+' pa.' avgTemp = (temperature+bmpTemp)/2 sonarMeasurements.append(distance) temperatureMeasurements.append(avgTemp) humidityMeasurements.append(humidity) pressureMeasurements.append(bmpPressure) except: print "Something happened... Fall back to previous measurement" if len(temperatureMeasurements) > 0: temperature = temperatureMeasurements[-1] humidity = humidityMeasurements[-1] pressure = pressureMeasurements[-1] sonarMeasurements.append(distance) temperatureMeasurements.append(temperature) humidityMeasurements.append(humidity) pressureMeasurements.append(pressure) else: print "Uh oh, got nothing to fall back on. Cancel this round." if len(sonarMeasurements) >= amountToAVG: avgSonar = 0 for _sonar in sonarMeasurements: avgSonar = avgSonar + _sonar avgSonar = avgSonar/amountToAVG sonarMeasurements = [] avgTemperature = 0 for _temperature in temperatureMeasurements: avgTemperature = avgTemperature + _temperature avgTemperature = avgTemperature/amountToAVG temperatureMeasurements = [] avgHumidity = 0 for _humidity in humidityMeasurements: avgHumidity = avgHumidity + _humidity avgHumidity = avgHumidity/amountToAVG humidityMeasurements = [] avgPressure = 0 for _pressure in pressureMeasurements: avgPressure = avgPressure + _pressure avgPressure = avgPressure/amountToAVG pressureMeasurements = [] print "----------------------------------------------------------------" print "Got Average." # Insert Data into the Database Table with db: insertCode = "INSERT INTO data values (NOW(), "+str(avgSonar)+" ,"+str(avgTemperature)+" ,"+str(avgHumidity)+" ,"+str(avgPressure)+")" curs.execute(insertCode) print "Average has been inserted into the table." print "----------------------------------------------------------------" gpio.output(yLEDPin, 0) time.sleep(frequency) x = x + 1 gpio.output(rLEDPin, 0) #gpio.output(gLEDPin, 1) print "================================================================" print "Finished Recording Data" print "Remember to run gpio.cleanup()!!!"
if dev_type not in [DHT11, DHT22, AM2302]: print 'Invalid sensor type, only 11, 22 and 2302 are supported for now!' exit(2) if dev_type == AM2302: dev_type = DHT22 if gpio_pin <= 0: print 'Invalid GPIO pin#' exit(3) dhtreader.init() sensor_values = None for cnt in xrange(20): sensor_values = dhtreader.read(dev_type, gpio_pin) if sensor_values: break if args.verbose: print "cnt", cnt time.sleep(3) if not sensor_values: print "sensor read timeout." exit(1) t, h = sensor_values temp = round(t, 0) humidity = round(h, 0)
import dhtreader type = 22 pin = 17 dhtreader.init() print dhtreader.read(type, pin)
def Main(): global state_led_big global bmp while 1: print('') cmd = raw_input("Was soll ich tun? ") if (len(cmd) == 0): Help() continue cmd = cmd.lower().split() if (cmd[0] in ['?', 'help', 'hilfe']): Help() continue elif (cmd[0] in ['e', 'q', 'end', 'ende']): break command = cmd[0] # Summer ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (command == 'summer'): if (len(cmd) == 2): switch = cmd[1] if (switch == 'ein') or (switch == 'aus'): switch = GetIOConst(switch) Buzzer(switch) else: Help() else: Help() continue # LED +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (command == 'led'): if (len(cmd) == 3): light = cmd[1] switch = cmd[2] if (switch == 'ein') or (switch == 'aus'): switch = GetIOConst(switch) if (light == 'rot'): Light(pin_led_red,switch) elif (light == 'grün'): Light(pin_led_green,switch) elif (light == 'blau'): Light(pin_led_blue,switch) elif (light == 'gelb'): Light(pin_led_yellow,switch) elif (light == 'weiß'): Light(pin_led_white,switch) elif (light == 'hellgelb'): Light(pin_led_bright_yellow,switch) elif (light == 'groß'): Light(pin_led_big,switch) state_led_big = switch else: Help() else: Help() else: Help() continue # Muster ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (command == 'muster'): if (len(cmd) == 4): led_pattern = cmd[1] led_pattern_delay = cmd[2] iterations = cmd[3] if not led_pattern.isdigit() \ or not led_pattern_delay.isdigit() \ or not iterations.isdigit(): Help() continue led_pattern = int(led_pattern) led_pattern_delay = float(led_pattern_delay) iterations = int(iterations) if (led_pattern < 1) or (led_pattern > len(led_patterns)): Help() continue if (led_pattern_delay < 2) or (led_pattern_delay > 60000): Help() continue if (iterations < 1) or (iterations > 1000): Help() continue Pattern(led_pattern-1,led_pattern_delay/1000,iterations) else: Help() continue # All actors ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (command == 'alles'): switch = cmd[1] if (switch == 'ein') or (switch == 'aus'): switch = GetIOConst(switch) AllActors(switch) else: Help() continue # Sensor ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (command == 'sensor'): i = 1 # außen # while (i <= 5): try: print("Sensor 1, Try #{}".format(i)) t1, h1 = dhtreader.read(22,pin_sensor1_bcm) except TypeError: t1 = h1 = -99.99 i += 1 continue break i = 1 # innen # while (i <= 5): try: print("Sensor 2, Try #{}".format(i)) t2, h2 = dhtreader.read(22,pin_sensor2_bcm) except TypeError: t2 = h2 = -99.99 i += 1 continue break t_bmp = bmp.readTemperature() p_bmp = bmp.readPressure() CPUTemp = GetCPUTemperature() print("CPU Temperatur: {:.2f} °C".format(CPUTemp)) print("Temperatur DHT außen: {:.2f} °C".format(t1)) print("Luftfeuchtigkeit DHT außen: {:.2f} %".format(h1)) print("Temperatur DHT innen: {:.2f} °C".format(t2)) print("Luftfeuchtigkeit DHT innen: {:.2f} %".format(h2)) print("Temperatur BMP: {:.2f} °C".format(t_bmp)) print("Luftdruck BMP: {:.2f} hPa".format(p_bmp / 100.0)) continue # Help ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Help()
(datetime.datetime.now(),t,h) try: cursor.execute(sql) db.commit() except: db.rollback() db.close() return isFanOn=False try: dhtreader.init() while(True): try: output = dhtreader.read(DHT11,dhtpin) if (output is not None): t, h = output if t and h: insertToMySql(t,h) #comment this line if you don't need to log into MySQL idx = t + (h *0.1) #adjust the idx based on your requirement, 38~40 is a good threshhold. if (idx > 40): #turn fan on if(not isFanOn): switch(relaypinA,GPIO.LOW) isFanOn=True print("{2}: Temp = {0} *C, Hum = {1} %".format(t, h,datetime.datetime.now())) print("Turn the Fan On!") else:#turn fan off if(isFanOn): switch(relaypinA,GPIO.HIGH) isFanOn=False
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import requests from requests.auth import HTTPBasicAuth import dhtreader type = 22 pin = 27 dhtreader.init() t, h = dhtreader.read(type, pin) humidity = "%2.2f" % (h) basicID = 'BASICID' basicPASS = '******' url = 'http://133.242.144.202/post' auth = HTTPBasicAuth(basicID, basicPASS) headers = {'content-type': 'application/json'} json_data = {"humidity": humidity} tag = "shibuhouse.1f.humidity" data = json.dumps(json_data) param = {'tag': tag, 'data': data} r = requests.post(url, params=param, headers=headers, auth=auth)
#!/usr/bin/python import dhtreader import time dhtPin = 4 dhtreader.init() temperature = None humidity = None while True: try: temperature, humidity = dhtreader.read(22, dhtPin) except: print('Error reading sensor') if isinstance(temperature, float) and isinstance(humidity, float): with open('TEMP', 'w') as t: t.write('{0:.2f}'.format(temperature)) with open('HUMIDITY','w') as h: h.write('{0:.2f}'.format(humidity)) print(str(temperature) + " " + str(humidity)) time.sleep(3)
dhtreader.init() if len(sys.argv) != 3: print("usage: {0} [11|22|2302] GPIOpin#".format(sys.argv[0])) print("example: {0} 2302 Read from an AM2302 connected to GPIO #4".format( sys.argv[0])) sys.exit(2) dev_type = None if sys.argv[1] == "11": dev_type = DHT11 elif sys.argv[1] == "22": dev_type = DHT22 elif sys.argv[1] == "2302": dev_type = AM2302 else: print("invalid type, only 11, 22 and 2302 are supported for now!") sys.exit(3) dhtpin = int(sys.argv[2]) if dhtpin <= 0: print("invalid GPIO pin#") sys.exit(3) print("using pin #{0}".format(dhtpin)) t, h = dhtreader.read(dev_type, dhtpin) if t and h: print("Temp = {0} *C, Hum = {1} %".format(t, h)) else: print("Failed to read from sensor, maybe try again?")
def run(self): try: temp, humid = dhtreader.read(22, self.parent.pinnum) except Exception: temp, humid = dhtreader.lastData dhtreader.lastData = (temp, humid)
dhtreader.init() if len(sys.argv) != 3: print(("usage: {0} [11|22|2302] GPIOpin#".format(sys.argv[0]))) print(("example: {0} 2302 Read from an AM2302 connected to GPIO #4".format(sys.argv[0]))) sys.exit(2) dev_type = None if sys.argv[1] == "11": dev_type = DHT11 elif sys.argv[1] == "22": dev_type = DHT22 elif sys.argv[1] == "2302": dev_type = AM2302 else: print("invalid type, only 11, 22 and 2302 are supported for now!") sys.exit(3) dhtpin = int(sys.argv[2]) if dhtpin <= 0: print("invalid GPIO pin#") sys.exit(3) print(("using pin #{0}".format(dhtpin))) t, h = dhtreader.read(dev_type, dhtpin) if t and h: print(("Temp = {0} *C, Hum = {1} %".format(t, h))) else: print("Failed to read from sensor, maybe try again?")
def run(self): try: t, h = dhtreader.read(22,self.parent.pinNum) except Exception: t, h = dhtreader.lastData dhtreader.lastData = (t,h)
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import requests from requests.auth import HTTPBasicAuth import dhtreader type = 22 pin = 27 dhtreader.init() t, h = dhtreader.read(type, pin) humidity = "%2.2f" % (h) basicID = 'BASICID' basicPASS = '******' url = 'http://133.242.144.202/post' auth = HTTPBasicAuth(basicID, basicPASS) headers = {'content-type': 'application/json'} json_data = {"humidity":humidity} tag = "shibuhouse.1f.humidity" data = json.dumps(json_data) param = {'tag':tag, 'data':data} r = requests.post(url, params=param, headers=headers, auth=auth)
import time type = 22 pin = 4 data1 = 12.454554545454 data2 = round(data1,0) data3 = "%.4f" % data1 dhtreader.init() i = 1 while i < 20: data = dhtreader.read(type, pin) if data != None: #feuchtigkeit = data[1] #Temperatur = data[0] i = i+1 #print(feuchtigkeit) #print(Temperatur) print(data) time.sleep(2)