def measure_and_write(): print('Logging sensor measurements to {0}.'.format(GDOCS_SPREADSHEET_NAME)) # login worksheet = login_open_sheet(GDOCS_OAUTH_JSON, GDOCS_SPREADSHEET_NAME) # Attempt to get sensor reading. humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN) # Skip to the next reading if a valid measurement couldn't be taken. # This might happen if the CPU is under a lot of load and the sensor # can't be reliably read (timing is critical to read the sensor). while humidity is None or temp is None: time.sleep(2) humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN) print('Temperature: {0:0.1f} C'.format(temp)) print('Humidity: {0:0.1f} %'.format(humidity)) # Append the data in the spreadsheet, including a timestamp worksheet.append_row([ '=TO_DATE(DATEVALUE("{0}")+TIMEVALUE("{0}"))'.format( str(datetime.datetime.now())), temp, humidity], value_input_option = 'USER_ENTERED' ) # Wait 30 seconds before continuing print('Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME))
def get_value(self): humidity, temp = dht.read(dht.DHT22, self.gpio_pin) if humidity is None or temp is None: time.sleep(.200) return list(dht.read(dht.DHT22, self.gpio_pin)) else: return [humidity, temp]
def celsius_farenhiet_convert(self): global celsius celsius = not celsius self.ui.plainTextEdit_2.setPlainText("C-F/F-C button pressed") humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) if humidity is None and temperature is None: for try_to_get_temp in range(0, 5): humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) if humidity is not None and temperature is not None: break if celsius == 0 and temperature is not None: self.ui.Temp_units.setText("F") temporary = self.ui.lineEditTempThreshold.text() temp1 = float(temporary) temporary1 = ((temp1 * 1.8) + 32.00) self.ui.lineEditTempThreshold.setText(str(temporary1)) self.ui.labelTempOutput.setText( str((float(temperature) * 1.8) + float(32))) self.ui.DisplayCurrentValue_Temp.setText( str((temperature * 9 / 5) + 32)) elif temperature is not None: temporary = self.ui.lineEditTempThreshold.text() self.ui.Temp_units.setText("C") temporary2 = ((0.555) * (float(temporary) - 32.00)) temporary2 = round(temporary2) self.ui.lineEditTempThreshold.setText(str(temporary2)) self.ui.labelTempOutput.setText(str(temperature)) self.ui.DisplayCurrentValue_Temp.setText(str(temperature))
def GetValueButtonFxn(self): global celsius print("GetValueButtonClicked") #self.ui.label.setText("Button Clicked") self.ui.plainTextEdit_2.setPlainText("Get Values button pressed") humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) if humidity is None and temperature is None: for try_to_get_temp in range(0, 5): humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) if humidity is not None and temperature is not None: break if temperature is not None and humidity is not None: humidity = round(humidity, 2) temperature = round(temperature, 2) timestamp = datetime.datetime.now() self.ui.labelHumidOutput.setText(str(humidity)) self.ui.labelTimestampOut.setText(str(timestamp)) if celsius == 1: self.ui.labelTempOutput.setText(str(temperature)) else: self.ui.labelTempOutput.setText(str((temperature * 9 / 5) + 32)) else: timestamp = datetime.datetime.now() self.ui.labelHumidOutput.setText("-") self.ui.labelTimestampOut.setText("-") self.ui.labelTempOutput.setText("-")
def readSensors(sensor_type, sensor_pin_4_inside, sensor_pin_22_outside, bool_sensor_retry): timestamp = datetime.now() if bool_sensor_retry == True: humidity1, temperature1 = Adafruit_DHT.read_retry( sensor_type, sensor_pin_4_inside) humidity2, temperature2 = Adafruit_DHT.read_retry( sensor_type, sensor_pin_22_outside) sensorLogging.logger.info( f'Finished reading Adafruit_DHT.22, inside Temperature: {temperature1}C, Humdity: {humidity1}%' ) sensorLogging.logger.info( f'Finished reading Adafruit_DHT.22, outside Temperature: {temperature2}C, Humdity: {humidity2}%' ) sensorLogging.logger.info( 'Resource stats: ' + f'CPU usage: {psutil.cpu_percent()}%, ' + f'Temperature: {CPUTemperature().temperature}C, ' + f'Memory usage: {psutil.virtual_memory()[2]}%') return (SensorValue(temperature1, humidity1, "inside"), SensorValue(temperature2, humidity2, "outside"), timestamp) else: humidity1, temperature1 = Adafruit_DHT.read(sensor_type, sensor_pin_4_inside) humidity2, temperature2 = Adafruit_DHT.read(sensor_type, sensor_pin_22_outside) if humidity1 is not None and temperature1 is not None and humidity2 is not None and temperature2 is not None: return (SensorValue(temperature1, humidity1, "inside"), SensorValue(temperature2, humidity2, "outside"), timestamp) else: raise Exception("retry off, not all reads succedded")
def timercheck(self): global timercount, my_timer if timercount == 30: print('Max count reached') self.timer.stop() sys.exit() else: print("Entered timer") timercount += 1 humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) timestamp = datetime.datetime.now() if humidity is None and temperature is None: for try_to_get_temp in range(0, 5): humidity, temperature = Adafruit_DHT.read( DHT_SENSOR, DHT_PIN) if humidity is not None and temperature is not None: break if temperature is not None and humidity is not None: humidity = round(humidity, 2) temperature = round(temperature, 2) val = (temperature, humidity, timestamp) mycursor.execute(sql, val) mydb.commit() application.update_readings(temperature, humidity, timestamp) print(mycursor.rowcount, "record inserted.", 'temp =', temperature, "humid=", humidity) else: application.update_readings(None, None, timestamp)
def sensor_loop(): while True: #sensors can be read about every two seconds. sometimes they dont read, #in which case we continue and wait another two seconds for a reading. time.sleep(2) #I would multiprocess this is it takes a really long time. upper_rh, upper_t = Adafruit_DHT.read(DHT22, upper_sensor) lower_rh, lower_t = Adafruit_DHT.read(DHT22, lower_sensor) if upper_rh is None or upper_t is None or lower_rh is None or lower_t is None: print("sensors", upper_rh, upper_t, lower_rh, lower_t) continue else: sensors = { "leaf_rh": round(upper_rh, 1), "leaf_t": round(upper_t, 1), "root_rh": round(lower_rh, 1), "root_t": round(lower_t, 1) } print(sensors) save_to_pickle(sensors)
def temp_und_luftfeuchtigkeit_messen(): sensor = ada.DHT22 # Da beim Auslesen die letzte Messung, die schon einige Zeit zurückliegen kann, abgerufen wird, fragen wir 2 mal in kurzem Abstand # Achtung: Die DHT22-Bibliothek scheint sich nicht darum zu scheren ob setmode mit BOARD oder BCM aufgerufen wurde. Sie verwendet die # übergebene PIN-Nummer im Sinne von BCM. D.h. PIN_DHT22=4 wird interpretiert als Pin GPIO4 und nicht Pin 7 auf dem Board h, t = ada.read(sensor, PIN_DHT22) time.sleep(6) h, t = ada.read(sensor, PIN_DHT22) n = 0 while ( not h or not t ) and n < 3: # Wenn kein Messwert vorliegt, versuchen wir es noch 3 mal time.sleep(6) h, t = ada.read(sensor, PIN_DHT22) n = n + 1 if not h or not t: logger.error("Messung fehlgeschlagen") return (None, None, None) else: h_abs = 1000 * luf.abs_feuchte(t, h) # Absolute Luftfeuchtigkeit wird auf Temperatur und rel. Feuchte errechnet logger.debug( 'Temperatur: {0:0.1f}*C rel.Luftfeuchtigkeit: {1:0.1f}% abs.Luftfeuchtigkeit: {2:0.3f} g/m³' .format(t, h, h_abs)) return (round(t, 1), round(h, 1), round(h_abs, 1))
def getData(self, i): if i==1: u, t = Adafruit_DHT.read(Adafruit_DHT.DHT11, 4) elif i==2: u, t = Adafruit_DHT.read(Adafruit_DHT.DHT11, 17) elif i==3: u, t = Adafruit_DHT.read(Adafruit_DHT.DHT22, 27) # funciona ok #umid3, temp3 = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 27) return t, u
def get_latest_values(self): global flag _translate = QtCore.QCoreApplication.translate humidity, temperature = Adafruit_DHT.read( DHT_SENSOR, DHT_PIN) #Read value from sensor #If value not obtained, try for a max of 10 times until value is obtained if humidity is None and temperature is None: for i in range(0, 10): humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) if humidity is not None and temperature is not None: print("Got Temperature, Breaking Loop") break if humidity is not None and temperature is not None: formated_temperature = '{0:0.1f}'.format( temperature) #Format Temperature up to 1 digit precision formated_humidity = '{0:0.1f}'.format( humidity) #Format Humidity up to 1 digit precision current_time = QtCore.QDateTime.currentDateTime().toString() payload = '{ "Msg_type": "data" , "timestamp": "' + current_time + '","temperature": ' + str( formated_temperature) + ',"humidity": ' + str( formated_humidity) + ' }' print(payload) myMQTTClient.publish("my/lambda/topic", payload, 0) if flag == 0: formated_temperature_C = formated_temperature self.tempLatestValue.setText( _translate("MainWindow", formated_temperature_C)) self.humLatestValue.setText( _translate("MainWindow", formated_humidity)) self.timeLatestValue.setText( _translate("MainWindow", current_time)) print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format( float(formated_temperature_C), humidity)) print("TimeStamp:", current_time) elif flag == 1: formated_temperature_F = ((float(formated_temperature) * 1.8) + 32) print('{0:0.1f}'.format(formated_temperature_F)) self.tempLatestValue.setText( _translate("MainWindow", str('{0:0.1f}'.format(formated_temperature_F)))) self.humLatestValue.setText( _translate("MainWindow", formated_humidity)) self.timeLatestValue.setText( _translate("MainWindow", current_time)) print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format( float(formated_temperature_F), humidity)) print("TimeStamp:", current_time) else: payload = '{ "Msg_type": "alert" , "Sensor Status": "Sensor Disconnected" }' myMQTTClient.publish("my/lambda/topic", payload, 0) print("Failed to retrieve data from humidity sensor")
def on_message(self, message): print('message received: %s' % message) if message == "Temperature": #make a dictionary humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) #If value not obtained, try for a max of 10 times until value is obtained if humidity is None and temperature is None: for i in range(0, 10): humidity, temperature = Adafruit_DHT.read( DHT_SENSOR, DHT_PIN) if humidity is not None and temperature is not None: print("Got Temperature, Breaking Loop") break if humidity is None and temperature is None: humidity = -1 temperature = -1 latest_data = {"temp": temperature, "hum": humidity} #turn it to JSON and send it to the browser self.write_message(json.dumps(latest_data)) elif message == "Get_Ten_Latest_Values": ''' humArray = [0,0,0,0,0,0,0,0,0,0] #Initialize humidity array tempArray = [0,0,0,0,0,0,0,0,0,0] #Initialize temp array for i in range(10): humidity,temperature = Adafruit_DHT.read_retry(DHT_SENSOR,DHT_PIN) humArray[i] = humidity tempArray[i] = temperature print("Humidity " ,i, "=" ,humArray[i]) print("Temperature " ,i, "=", tempArray[i]) self.write_message(str(humArray)) ''' #Get last 10 values of humidity from database sqlHumTenArray = tordbu.getLastTenHumidityValues() humArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #Initialize the array for i in range(10): humArray[9 - i] = sqlHumTenArray[i][0] self.write_message(str(humArray)) elif message == "Temperature Graph": with open("temperature.png", "rb") as imageFile: imgStr = base64.b64encode(imageFile.read()) self.write_message(imgStr) elif message == "Humidity Graph": with open("humidity.png", "rb") as imageFile: imgStr = base64.b64encode(imageFile.read()) self.write_message(imgStr)
def get_latest_values(self): global flag _translate = QtCore.QCoreApplication.translate humidity, temperature = Adafruit_DHT.read( DHT_SENSOR, DHT_PIN) #Read value from sensor #If value not obtained, try for a max of 10 times until value is obtained if humidity is None and temperature is None: for i in range(0, 10): humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) if humidity is not None and temperature is not None: print("Got Temperature, Breaking Loop") break if humidity is not None and temperature is not None: formated_temperature = '{0:0.1f}'.format( temperature) #Format Temperature up to 1 digit precision formated_humidity = '{0:0.1f}%'.format( humidity) #Format Humidity up to 1 digit precision current_time = QtCore.QDateTime.currentDateTime().toString() if flag == 0: formated_temperature_C = formated_temperature self.tempLatestValue.setText( _translate("MainWindow", formated_temperature_C)) self.humLatestValue.setText( _translate("MainWindow", formated_humidity)) self.timeLatestValue.setText( _translate("MainWindow", current_time)) print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format( float(formated_temperature_C), humidity)) print("TimeStamp:", current_time) elif flag == 1: formated_temperature_F = ((float(formated_temperature) * 1.8) + 32) print('{0:0.1f}'.format(formated_temperature_F)) self.tempLatestValue.setText( _translate("MainWindow", str('{0:0.1f}'.format(formated_temperature_F)))) self.humLatestValue.setText( _translate("MainWindow", formated_humidity)) self.timeLatestValue.setText( _translate("MainWindow", current_time)) print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format( float(formated_temperature_F), humidity)) print("TimeStamp:", current_time) else: print("Failed to retrieve data from humidity sensor")
def get_humidity_temperature(): for i in range(10): humidity, temperature = Adafruit_DHT.read(dht, pin) if humidity is not None and humidity > 20 and humidity < 100 and temperature is not None: return (humidity, temperature) time.sleep(0.1) return (-1, -100)
def update_external_readings(state, payload, sensor, pin): """ This function reads the temperature and the humidity from sensor and updates the state variables Args: state (dictionary): The state variables dictionary payload (dictionary): The payload variables dictionary sensor (Adafruit_DHT): The Adafruit_DHT reference for the sensor used pin (integer): The GPIO pin where the sensor is connected Returns: No returns """ end_delay = time.time() if (end_delay - state["start_delay"] > 10 and state["reading_enable"]): umid, temp = Adafruit_DHT.read(sensor, pin) if umid is not None and temp is not None: payload["umid_ext"] = umid payload["temp_ext"] = temp state["start_delay"] = time.time()
def Get_Param(self): """ This function gets sensor data and populates the textboxes """ _translate = QtCore.QCoreApplication.translate #Select sensor module and pin sensor_module = Adafruit_DHT.DHT22 sensor_pin = 4 #Read sensor data with a delay time.sleep(2.3) humidity, temperature = Adafruit_DHT.read(sensor_module, sensor_pin) #Get current time timenow = datetime.datetime.time(datetime.datetime.now()) #Check for sensor data and display values accordingly if humidity is not None and temperature is not None: self.textEdit.setText( _translate("MainWindow", str(round(temperature, 2)) + " C")) self.textEdit_2.setText( _translate("MainWindow", str(round(humidity, 2)) + " %")) self.textEdit_3.setText(_translate("MainWindow", "Connected!")) self.textEdit_4.setText(_translate("MainWindow", str(timenow))) else: self.textEdit.setText(_translate("MainWindow", "N/A")) self.textEdit_2.setText(_translate("MainWindow", "N/A")) self.textEdit_3.setText(_translate("MainWindow", "Not Connected!")) self.textEdit_4.setText(_translate("MainWindow", "N/A"))
def DHT11_read(): # Érzékelő típusának beállítása : DHT11,DHT22 vagy AM2302 # A szenzorunk a következő GPIO-ra van kötve: global temp, hum, max_hum, max_temp, min_temp, min_hum, avg_hum, avg_temp, col_temp, col_hum, req_temp, req_hum, req_temp, req_temp gpio = 17 # Ha a read_retry eljárást használjuk. Akkor akár 15x is megpróbálja kiolvasni az érzékelőből az adatot (és minden olvasás előtt 2 másodpercet vár). # humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, gpio) humidity, temperature = Adafruit_DHT.read(Adafruit_DHT.DHT11, gpio) # A DHT11 kiolvasása nagyon érzékeny az időzítésre és a Pi alkalmanként # nem tud helyes értéket kiolvasni. Ezért megnézzük, hogy helyesek-e a kiolvasott értékek. if humidity is not None and temperature is not None: temp = temperature hum = humidity if temp < min_temp: min_temp = temp if temp > max_temp: max_temp = temp col_temp += int(temp) req_temp += 1 avg_temp = int(col_temp / req_temp) if hum < min_hum: min_hum = hum if hum > max_hum: max_hum = hum col_hum += int(hum) req_hum += 1 avg_hum = int(col_hum / req_hum) else: return "", ""
def senseDHT(): humidity, temperature = Adafruit_DHT.read(Adafruit_DHT.DHT11, '4') if temperature is not None: return ('Temp={0:0.1f}* Humidity={1:0.1f}%'.format( temperature, humidity)) else: return ('Fail to read DHT')
def _read_am2302(pin, para): #http://www.home-automation-community.com/temperature-and-humidity-from-am2302-dht22-sensor-displayed-as-chart/ with Timeout(seconds=2.5): humidity, temperature = Adafruit_DHT.read(Adafruit_DHT.AM2302, pin) if para == 'temperature': v = float(temperature) if v > 150.: print '_read_am2302: temperature is too high %s' % v raise BaseException('temperature is too high %s' % v) if v < -55.: print '_read_am2302: temperature is too low %s' % v raise BaseException('temperature is too low %s' % v) return v elif para == 'humidity': v = float(humidity) if v > 100.: print 'humidity is too high %s' % v raise BaseException('humidity is too high %s' % v) if v < 0.: print 'humidity is too low %s' % v raise BaseException('humidity is too low %s' % v) return v else: print '! _read_am2302: para should be either temperatue or humidity' raise BaseException('para should be either temperatue or humidity')
def read(self): humidity, temperature = Adafruit_DHT.read(sensor, pin) if humidity is not None and temperature is not None: temperature = 9.0/5.0*temperature + 32.0 return {"AirTemperature": temperature, "Humidity": humidity} else: return {"AirTemperature": 0, "Humidity": 0}
def __init__(self, main, framework, update_interval=5000): """This starts the background and continuous tasks like humidity and temperature control""" Thread.__init__(self) self.main = main self.framework = framework self.stop_measurement_loop = self.main.stop_measurement_loop self.update_interval = float(update_interval) self.queue_to_main = framework["Message_to_main"] self.settings = framework["Configs"]["config"]["settings"] self.sensors = self.settings["Sensors"] self.log = logging.getLogger(__name__) self.running = False # First try if DHT resource is valid and accessible self.success_DHT = False try: import Adafruit_DHT for name, sensor in self.sensors.items(): sensortype = getattr(Adafruit_DHT, sensor["type"]) humidity, temperature = Adafruit_DHT.read( sensortype, sensor["pin"]) if not humidity and not temperature: self.log.critical( "Sensor {} at pin {} for room {} did not answer.". format(sensortype, sensor["pin"], name)) self.success_DHT = True except Exception as e: self.log.error( "The temperature and humidity controller seems not to be responding. Error:" + str(e))
def get_DHT22_humidity(cmd, message, recdata, DHT22_data): successflag = 0 msgarray = message.split(":") pin = int(msgarray[1]) deltat = datetime.datetime.now() - DHT22_data['lastupdate'] if deltat.total_seconds() > 2: humidity = None temperature = None try: sensor = Adafruit_DHT.DHT22 humidity, temperature = Adafruit_DHT.read(sensor, pin) except: print "error reading the DHT sensor (Humidity,Temperature)" logger.exception("message") if (humidity is not None) and (temperature is not None): print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format( temperature, humidity) DHT22_data['Humidity'] = ('{:3.2f}'.format(humidity / 1.)) DHT22_data['Temperature'] = ('{:3.2f}'.format(temperature / 1.)) DHT22_data['lastupdate'] = datetime.datetime.now() successflag = 1 else: print 'Failed to get DHT22 reading' else: successflag = 1 # use the data in memory, reading less than 2 sec ago recdata.append(cmd) recdata.append(DHT22_data['Humidity']) recdata.append(successflag) return DHT22_data['lastupdate']
def GetHumidityTemperature(): global temp, hum humidity, temperature = Adafruit_DHT.read(11, pin) if humidity != None and temperature != None: temp = temperature hum = humidity return hum, temp
def read_humidity(self, DHT_PIN = 27): """ DHT_PIN: PIN where the DHT sensor is connected to :return: the humidity value collected from the DHT22 sensor """ import Adafruit_DHT # reading data from the DHT 22 sensor DHT_TYPE = Adafruit_DHT.DHT22 humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN) error_num = 0 if humidity is None or temp is None: # this if statement makes sure data is received from the sensor. if not, it will keep going to the beginning of # the while loop error_num += 1 if error_num > 5: print ("Something's wrong...please check the connection to the sensor") # I am putting this in a try/except block because sometimes the sensor doesn't return data so instead of # the program crashing, you see the error. try: humidity = format(humidity, '.2f') except Exception as e: print (e) return humidity
def run(self): "poll the device" while not self.quit_event.is_set(): values = Adafruit_DHT.read(self.sensor, self.pin) if (values[0] or values[1]) is not None: self.last_value = HumidityTemparture(*values) time.sleep(self.delay)
def sensor(self): # # uncomment if running with actual sensor sensor = Adafruit_DHT.DHT22 pin = 4 # pin 7 on rpi 3 is GPIO 4 humidity, temperature = Adafruit_DHT.read( sensor, pin) #Changed to read() from read_retry() #error case if humidity is None or temperature is None: self.ui.status.setText('status: Sensor is not working!!!') return t_f = round((temperature * 9) / 5 + 32) #self.temp_f = (temperature*9)/5 + 32.0 self.temp_c = temperature self.hum = humidity self.temp_f = (temperature * 9) / 5 + 32.0 t_f = round((temperature * 9) / 5 + 32) unix = int(time.time()) date = str( datetime.datetime.fromtimestamp(unix).strftime( '%Y-%m-%d %H:%M:%S')) self.ui.status.setText("status: Temperature - " + str(int(self.temp_f)) + "deg F / " + str(int(self.temp_c)) + "deg C || Humidity: " + str(int(self.hum)) + "% || Date/Time: " + date) message1 = json.dumps({ "TemperatureinC": int(temperature), "Humidity": str(humidity) }) c.execute( "INSERT INTO SENSOR (dateandtime, TEMPERATUREinC,TEMPERATUREinF,HUMIDITY) VALUES (%s, %s, %s, %s)", (date, temperature, t_f, humidity)) mqtt_client.publish("EID_Project3", message1, 0) conn.commit()
def loop(self): while True: if not data_container.DataContainer.get_instance().sensor_lock: humid, temp = dht.read(dht.DHT11, self.data_pin) self._humid = humid if humid else self._humid self._temp = temp if temp else self._temp time.sleep(self.POLL_TIME)
def __init__(self): super(AppWindow, self).__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) humidity, temperature = Adafruit_DHT.read(22, 4) if humidity is None and temperature is None: print('The sensor must be disconnected') self.ui.sensor_stat.setText('Sensor is disconnected') else: self.ui.sensor_stat.setText('Sensor is connected') temp = '{0:0.1f}'.format(temperature) hum = '{0:0.1f}%'.format(humidity) self.ui.temp_val.setText(temp) self.ui.hum_val.setText(hum) self.ui.avg_temp.setText(temp) self.ui.avg_hum.setText(hum) self.ui.temp_level.setValue(float(temperature)) self.ui.hum_level.setValue(float(humidity)) self.ui.time_req.setText(time.ctime()) self.ui.refresh.clicked.connect(self.ui.time_req.clear) self.ui.refresh.clicked.connect(self.ui.temp_val.clear) self.ui.refresh.clicked.connect(self.ui.hum_val.clear) self.ui.cel_faran.clicked.connect(self.Cel_Faran) self.ui.pushButton_3.clicked.connect(self.Exit) self.ui.refresh.clicked.connect(self.SensorReadings) self.ui.alarm.setText('NO ALARM') self.ui.temp_alarm.valueChanged.connect(self.valuechange) self.ui.hum_alarm.valueChanged.connect(self.valuechange) self.ui.gen_graph.clicked.connect(self.Graph)
def getDataFahrenheit(self): global count humidity, temperature = Adafruit_DHT.read(22, 4) if humidity and temperature is None: self.SensorState.setText("Disconnected") if humidity and temperature is not None: self.SensorState.setText("Connected") tempf = (float(temperature) * (9 / 5.0)) + 32 temp_data = '{0:.2f}'.format(tempf) humid_data = '{0:.2f}'.format(humidity) pydict = {'Temperature': temp_data, 'Humidity': humid_data} jsondict = json.dumps(pydict) mqttaws_client.publish(topic, jsondict, 1) self.TempLastValue.setText(temp_data) self.HumLastValue.setText(humid_data + '%') self.humiditysum += float(humidity) self.temperaturesum += float(tempf) averagehumidity = (self.humiditysum / float(self.count)) averagetemperature = (self.temperaturesum / float(self.count)) average_humid_data = '{0:.2f}'.format(averagehumidity) average_temp_data = '{0:.2f}'.format(averagetemperature) self.HumAverageValue.setText('{0:.2f}'.format(averagehumidity) + '%') self.TempAverageValue.setText('{0:.2f}'.format( (averagetemperature)) + 'degF') self.count += 1 if (tempf > self.maximumtemperature): self.maximumtemperature = tempf if (humidity > self.maximumhumidity): self.maximumhumidity = humidity if (tempf < self.minimumtemperature): self.minimumtemperature = tempf if (humidity < self.minimumhumidity): self.minimumhumidity = humidity max_temp_data = '{0:.2f}'.format(self.maximumtemperature) min_temp_data = '{0:.2f}'.format(self.minimumtemperature) max_humid_data = '{0:.2f}'.format(self.maximumhumidity) min_humid_data = '{0:.2f}'.format(self.minimumhumidity) self.TempMaxValue.setText('{0:.2f}'.format( (self.maximumtemperature)) + 'degF') self.HumMaxValue.setText('{0:.2f}'.format(self.maximumhumidity) + '%') self.TempMinValue.setText('{0:.2f}'.format( (self.minimumtemperature)) + 'degF') self.HumMinValue.setText('{0:.2f}'.format(self.minimumhumidity) + '%') with open('data.csv', 'a', newline='') as datafile: file_write = csv.writer(datafile, delimiter=',') file_write.writerow([ temp_data, max_temp_data, min_temp_data, average_temp_data, humid_data, max_humid_data, min_humid_data, average_humid_data, self.getTime() ]) else: with open('data.csv', 'a', newline='') as datafile: file_write = csv.writer(datafile, delimiter=',') file_write.writerow([0, 0, 0, 0, 0, 0, 0, 0, self.getTime()]) print("No Data Sensed")
def read(sensor, pin, db=None): '''Tenta fazer a leitura 100 vezes, com um intervalo de 2 s entra tentativas, até desistir e jogar a toalha. Depois grava o resultado no banco de dados.''' if sensor not in sensor_args: print("Sensor {} não suportado".format(sensor)) return for i in range(100): humidity, temperature = Adafruit_DHT.read(sensor_args[sensor], pin) valid_humidity = humidity is not None and 10 <= humidity <= 100 valid_temperature = temperature is not None and -5 <= temperature <= 50 if valid_humidity and valid_temperature: break else: humidity = temperature = None sleep(2) temperature = round(temperature, 1) humidity = round(humidity, 1) if db is not None: db.salva_dht(temperature, humidity) if temperature: temperature = "{0:0.1f}".format(temperature) if humidity: humidity = "{0:0.1f}".format(humidity) print('Temp={}* Humidity={}%'.format(temperature, humidity))
def TempAndHumidityLCD(lcdColumns, lcdRows, tempSensor, tempPin): # Initialize the LCD using the pins lcd = LCD.Adafruit_CharLCDBackpack(address=0x21) temperature, humidity = Adafruit_DHT.read(tempSensor, tempPin) time.sleep(1) GPIO.cleanup() temperature = temperature * 9 / 5.0 + 32 temperatureStr = str(temperature) humidityStr = str(humidity) # print temp lcd.set_backlight(0) lcd.message("Current temp \n" + temperatureStr + " F") time.sleep(5.0) lcd.clear() # print humidity lcd.set_backlight(0) lcd.message("Current humidity \n" + humidityStr + " %") time.sleep(5.0) lcd.clear() GPIO.cleanup()
def get_DHT22(): humidity, temperature = Adafruit_DHT.read(DHTSensor, GPIO_DHT_Pin) if humidity is not None and temperature is not None: #print("Temperature={0:0.001f}C Humidity={1:0.001f}%".format(temperature, humidity)) return humidity, temperature else: print("DHT22 Sensor failure...")
def getRawValues(self): """ Get the raw values of humidty and temperature""" while True: humidity, temp = Adafruit_DHT.read(self.DHT_TYPE, self.dataPin) # Check if it worked if humidity is None or temp is None: time.sleep(self.sleepTime) continue else: return (humidity, temp)
def read_retry(self, sensor, pin, retries=25, delay_seconds=2): for i in range(retries): if not self.running: break humidity, temperature = Adafruit_DHT.read(sensor, pin) if ((humidity is not None and temperature is not None) and (humidity < 100)): return (humidity, temperature) time.sleep(delay_seconds) return (None, None)
def _iteration(self): humidity, temperature = Adafruit_DHT.read( Adafruit_DHT.DHT22, self.gpio_number, ) if humidity is None or temperature is None: raise SensorError() self.set_value('humidity', humidity) self.set_value('temperature', temperature)
def index(): try: #check to see if the DHT sensor is connected humidity, temperature = Adafruit_DHT.read(dh22_sensor, pin) #get the values from the sensor humidity ='{:.2f}'.format(humidity) #convert value to two decimal places temperature ='{:.1f}'.format(temperature) #convert value to one decimal place except: # If the sensor is not connected send null values humidity = 0 temperature = 0 pass try: # Read the light sensor data light_level = ReadChannel(light_channel) except: # If the sensor is not connected send null values light_level = 0 pass try: # Read the temperature sensor data temp_level = ReadChannel(temp_channel) temp = ConvertTemp(temp_level,2) except: temp = 0 pass try: battery = pijuice.status.GetChargeLevel()["data"] status = pijuice.status.GetStatus()["data"] power = status["powerInput"] charge = status["battery"] except: battery = 0 power = "Error" charge = "Error" pass #variables to pass through to the web page templateData = { 'humidity' : humidity, 'temperature' : temperature, 'light' : light_level, 'temp' : temp, 'battery' : battery, 'power' : power, 'charge' : charge } return render_template('index.html', **templateData) #when a html request has been made return these values
def read_sensors(self): self.gpio_functions.set_address(self.multipl_address) self.s_id = "DHTmulti{}".format(str(self.multipl_address).zfill(2)) attempts = 8 for i in range(attempts): humidity, temperature = Adafruit_DHT.read(Adafruit_DHT.DHT22, self.gpio_functions.data_pin) if (humidity and temperature) and humidity < 100.0 and humidity > 0.0: return self._format_output(humidity, temperature) else: print time.ctime() + ": reading {} sensors failed at attempt {}".format(self.s_id, i) time.sleep(2) return self._get_db_dict({"error": 1.0})
def getDHT(): """ Currently only trying to get the DHT sensor value once, if it fails I assign a 0 value to both the temp and humidity. Temp is converted to Fahrenheit. """ dht_humidity, cels = Adafruit_DHT.read(DHT_TYPE, DHT_PIN) if cels and dht_humidity: dht_temp = cels_fahr(cels) else: checkDebug("*** Unable to get DHT values! ***") dht_temp = 0 dht_humidity = 0 return dht_temp, dht_humidity
def temperature(self): """Return (temparature, humidity)""" try: #t, h = dhtreader.read(self.dhttype,self.dhtpin) t, h = Adafruit_DHT.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 GET(self): output = 'sensors:['; for sensor, pin in DHT_SENSORS.items(): logging.info('List - Sensor:' + sensor + ' Pin; ' + str(pin)) humidity, temp = Adafruit_DHT.read(DHT_TYPE, pin) if humidity is None or temp is None: logging.info('Data not returned') time.sleep(2) print 'sensor', sensor, datetime.datetime.now(), temp, humidity logging.info('List - Temperature: {0:0.1f} C'.format(temp)) logging.info('List - Humidity: {0:0.1f} %'.format(ambient)) output += "{'sensor': '" + Sensor + "'temp': '" + str(temp) + "'}," output += ']'; return output
def getValues(self): """Get the values for humidity and temperature""" while True: humidity, temp = Adafruit_DHT.read(self.DHT_TYPE, self.dataPin) # check to see if it worked if humidity is None or temp is None: time.sleep(self.sleepTime) continue else: # Adjust the humidity and temp humidity = ((humidity / 100.0) * (self.__MAX - self.__MIN) + self.__MIN) temp = (((temp + 40.0) / 120.0) * (self.__MAX - self.__MIN) + self.__MIN) return (humidity,temp)
def get_data(self): logger = logging.getLogger('hiverize.dht22') for i in range(1, 3): logger.debug('Reading data') try: humidity, temperature = Adafruit_DHT.read( Adafruit_DHT.DHT22, self.pinout) if humidity is not None and temperature is not None: return humidity, temperature #time.sleep(2) logger.warning('{}. DHT Measurement failed. Starting next try'.format(i)) except ValueError: logger.debug('Sensor not found') return False, False
def publish_message(self): """If the class is not stopping, publish a message to RabbitMQ, appending a list of deliveries with the message number that was sent. This list will be used to check for delivery confirmations in the on_delivery_confirmations method. Once the message has been sent, schedule another message to be sent. The main reason I put scheduling in was just so you can get a good idea of how the process is flowing by slowing down and speeding up the delivery intervals by changing the PUBLISH_INTERVAL constant in the class. """ if self._stopping: return humidity, temperature = Adafruit_DHT.read(Adafruit_DHT.AM2302, config.PIN) if temperature == None: LOGGER.warn("Can't get temperature properly currently") def data_format(value): if value == None: return None return "%.1f" % value ifaces = [netifaces.ifaddresses(intf) for intf in netifaces.interfaces()] addresses = [] for iface in ifaces: if netifaces.AF_INET not in iface: continue addresses.extend([addr['addr'] for addr in iface[netifaces.AF_INET]]) addresses = [str(ip) for ip in [netaddr.IPAddress(x) for x in addresses] if ip.is_unicast() and not ip.is_reserved()] message = { "temp" : data_format(temperature), "humid" : data_format(humidity), "id": config.NODE_ID, "addresses": addresses } properties = pika.BasicProperties(app_id=config.NODE_ID, content_type='text/plain') self._channel.basic_publish('', self.ROUTING_KEY, json.dumps(message, ensure_ascii=False), properties) self._message_number += 1 self._deliveries.append(self._message_number) LOGGER.info('Published message # %i', self._message_number) self.schedule_next_message()
def collect_sample(sc,conn,cursor,session_id,subject_type,car_id): click.echo('Recording sample') now = datetime.datetime.now() image_name = '{}_{}.png'.format(session_id, now) frame = read_image() cv2.imwrite('image_data/{}'.format(image_name), np.uint8(frame)) # write it! _, temperature = Adafruit_DHT.read(sensor, pin) if temperature is None: click.echo('Failed to get temperature reading.') cursor.execute("INSERT INTO readings VALUES (?, ?, ?, ?, ?, ?)",(session_id, now, subject_type, car_id, temperature, image_name)) conn.commit() sc.enter(1, 1, collect_sample, (sc,conn,cursor,session_id,subject_type,car_id))
def getWeatherReading(): # Type of sensor, can be Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. DHT_TYPE = Adafruit_DHT.DHT22 # Example of sensor connected to Raspberry Pi pin 23 #DHT_PIN = 23 DHT_PIN = 4 # Example of sensor connected to Beaglebone Black pin P8_11 #DHT_PIN = 'P8_11' # Attempt to get sensor reading. humidity, temperature = Adafruit_DHT.read(DHT_TYPE, DHT_PIN) #print('get_weather_reading: ', humidity, temperature) if temperature is not None and humidity is not None: temperature = (temperature * 1.8) + 32 #convert C to F temperature = round(temperature, 2) humidity = round(humidity, 2) return (temperature, humidity)
def getReadingFromSensor(inputpin): attempts = 0 while attempts < 3: # Attempt to get sensor reading. humidity, temp = Adafruit_DHT.read(DHT_TYPE, inputpin) # Reading the sensor depends on timing so to make sure we are not busy anymore insert a little sleep # Skip to the next reading if a valid measurement couldn't be taken. # This might happen if the CPU is under a lot of load and the sensor # can't be reliably read (timing is critical to read the sensor). if humidity is None or temp is None: time.sleep(2) attempts += 1 continue print 'Temperature{0}: {1:0.1f} C'.format(inputpin,temp) print 'Humidity{0}: {1:0.1f} %'.format(inputpin,humidity) return temp, humidity
def read(self): """ Sometimes the sensor will return "None" This might happen if the CPU is under a lot of load and the sensor this property method attempts to read the dht22 3 times before logging an error will return 'NA' for failed values. """ attempts = 0 while attempts < 3: try: humidity, temp = Adafruit_DHT.read(self.sens_type, self.pin) if humidity and temp: return {"%s" % self.name: {"temp": round(float(temp), 1), "humidity": round(float(humidity), 1), "timestamp": datetime.datetime.utcnow().isoformat()}} logger.debug('%s DHT22 sensor read failed! Attempts remaining: {}'.format(self.name, 2-attempts)) raise TypeError('could not read sensor.') except TypeError: attempts += 1 time.sleep(2) logger.error('{}-DHT22 sensor could not be reached after 3 attempts. Make sure sensor is connected to GPIO {}'.format(self.name,str(self.pin))) return {"%s" % self.name: {"temp": 'NA', "humidity": 'NA',"timestamp": datetime.datetime.utcnow().isoformat()}}
def read_temp (debug_on): # Read the temperature from the DHT22 temperature sensor. while True: humidity, temperature = Adafruit_DHT.read(DHT_22,IN_MEASURE_TEMP_PIN ) # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! if humidity is not None and temperature is not None: if debug_on > 5: print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity) #my_logger.info ('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) temperature = temperature - TEMPERATURE_OFFSET update_measured_temp (temperature) time.sleep(10) else: if debug_on > 5: print 'Failed to get reading. Try again!' #my_logger.info('Failed to read temp') time.sleep(2)
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import time import datetime import Adafruit_DHT # Type of sensor, can be Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. DHT_TYPE = Adafruit_DHT.DHT11 # Sensor connected to Raspberry Pi pin... DHT_PIN = 10 humid, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN) #if humid is None or temp is None: # time.sleep(2) # continue print 'Temperature: {:.1f} °C'.format(temp) print 'Humidité: {:.1f} %'.format(humid)
hum = Humidity() hum.__init__() #----------------------------- Functionality ----------------------------------- # Toggle fan def toggle_fan(state): if state: subprocess.call(['sudo',codes.SENDER,codes.FAN_ON]) else: subprocess.call(['sudo',codes.SENDER,codes.FAN_OFF]) while True: # Read sensor humidity_reading, temp = Adafruit_DHT.read(codes.DHT_TYPE, codes.DHT_PIN) # If we can't get a reading we skip this one, sometimes we can't get a # measurement because reasons. if humidity_reading is None or temp is None: time.sleep(2) continue # Printing to standard output for testing purposes. print 'Humidity={0:0.1f}%'.format(humidity_reading) # Record the reading hum.record_reading(humidity_reading) if humidity_reading >= 40.0 and hum.is_fluctuating() and not fan_is_on: print 'Turning fan on!'
#!/usr/bin/python3 # coding=utf-8 import Adafruit_DHT # sensor type sensor = Adafruit_DHT.DHT_11 # use BCM pin=4 humidity,temperature = Adafruit_DHT.read(sensor,pin) if humidity is not None and temperature is not None: print "temperature: %.2f" % temperature print "humidity: %.2f" % humidity else: print "Fail! Please try again"
draw = ImageDraw.Draw(image) draw.text((positionX, positionY), status, font=font) disp.image(image) disp.display() # Display welcome image. displayImageStatus('lcd/bbb.png', 'Hello Person!', 14, 37) time.sleep(5) while True: # Get temperature data. humidity, celsius = Adafruit_DHT.read(DHT_TYPE, DHT_PIN) fahrenheit = (float(0 if celsius is None else celsius) * 1.8) + 32 # Skip to the next reading if a valid measurement couldn't be taken. if humidity is None or celsius is None or fahrenheit is None: time.sleep(5) continue print '---------------------------------' print 'Temperature: {0:0.1f} C'.format(celsius) print 'Temperature: {0:0.1f} F'.format(fahrenheit) print 'Humidity: {0:0.1f} %'.format(humidity) # Insert temperature data in mysql database. tempData = ('{0:0.1f}'.format(celsius), '{0:0.1f}'.format(fahrenheit), '{0:0.1f}'.format(humidity))
#Location, User, Password, DB db = MySQLdb.connect("localhost", "monitor", "raspberry", "temps") db.autocommit(True) curs = db.cursor() # zone, pin, sensortype sensor = ['dht01', 2, Adafruit_DHT.DHT11] # How long to wait (in seconds) between measurements FREQ_MEASURE = 10 print 'Logging temp/humidity to MySQL database every {0} seconds.'.format(FREQ_MEASURE) while True: # Attempt to get sensor reading. humidity, temp = Adafruit_DHT.read(sensor[2], sensor[1]) if humidity is None or temp is None: time.sleep(1) continue temp = '{0:0.1f}'.format(temp) humidity = '{0:0.1f}'.format(humidity) #print str(temp) + " " + str(humidity) + "\n" insertQuery = """ INSERT INTO tempdat (`tdate`, `ttime`, `zone`, `temperature`, `humidity`) VALUES (CURRENT_DATE(), NOW(), 'th', %s, %s) """
def update_measured_temp (temp): write_measured_temp_to_file (temp) #--------------------------------------------------------------------------------- # Main thread: my_logger = init_logging() debug_level = DEBUG_LEVEL_0 # Read the temperature from the DHT22 temperature sensor. while True: humidity, temperature = Adafruit_DHT.read(DHT_22,IN_MEASURE_TEMP_PIN ) # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! if humidity is not None and temperature is not None: my_logger.info (',{0:0.1f},{1:0.1f}'.format(temperature, humidity)) update_measured_temp (temperature) time.sleep(10) else: my_logger.debug ('Failed to get reading. Try again!') time.sleep(2)
def readSensor(self): return Adafruit_DHT.read(self.DHT_TYPE, self.DHT_PIN)
camera = picamera.PiCamera() # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! print "\n\n" while True: # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). GPIO.output(LED_GPIOPIN,True) humidity, temperature = Adafruit_DHT.read(DHT_TYPE, DHT_GPIOPIN) NOW = datetime.datetime.now() if humidity is None and temperature is None: print 'skip' GPIO.output(LED_GPIOPIN,False) time.sleep(FREQUENCY_SKIP) continue #print datetime.datetime.now().strftime("%Y-%b-%d %H:%M:%S") print datetime.datetime.now().strftime("%Y-%b-%d %H:%M:%S") + '\tTemp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity) GPIO.output(LED_GPIOPIN,False) if temperature > 18 camera.capture('/home/pi/scripts/cam-shots/img' + datetime.datetime.now().strftime("%Y%b%d_%H%M%S") + '.jpg')
else: print 'Failed to update sensor data to device id \'{0}\' with message {1}.'.format(sensor_lists['deviceid'], result['Message']) else: print 'Failed to update sensor data to device id \'{0}\' with http error code {1}.'.format(sensor_lists['deviceid'], r.status_code) print 'Logging sensor measurements to lewei every {0} seconds.'.format(FREQUENCY_SECONDS) print 'Press Ctrl-C to quit.' sensor_lists = None ATTEMPS = 5 while True: if sensor_lists == None: sensor_lists = get_sensor_lists(userkey, deviceid) # Attempt to get sensor reading. humidity, temp = Adafruit_DHT.read(sensor, pin) # Skip to the next reading if a valid measurement couldn't be taken. # This might happen if the CPU is under a lot of load and the sensor # can't be reliably read (timing is critical to read the sensor). attemp = 1 if humidity is None or temp is None: if attemp <= ATTEMPS: attemp += 1 time.sleep(2) continue else: print 'Failed to get data from sensor after attempting {0} times.'.format(ATTEMPS) sys.exit(1) print 'Temperature: {0:0.1f} C'.format(temp)
def readSensor(self): import Adafruit_DHT sensor = Adafruit_DHT.DHT11 self.humidity, self.temperature = Adafruit_DHT.read(sensor, SENSOR_PIN) self.mesureTime = time.time()
# Emplacement du fichier JSON d'enregistrement des mesures foldername = '/mnt/rasponline/' # Nom de fichier sans extension (la mettra tout seul) filename = 'TEMP3' # Je liste les offsets des capteurs ici (en degres celcius (ecart entre valeur lue et valeur reelle) sensoroffset = [0.00 , 0.00] # definition des listes de valeurs des sondes listtemp = list() listhum = list() Error = 0 # lecture six fois des valeurs BMP180 et SI1145 et stockage en listes for pollloop in range(0,15) : humidity, temperature = Adafruit_DHT.read(Adafruit_DHT.AM2302, 4) if humidity is not None and temperature is not None: listtemp.append(temperature) listhum.append(humidity) else: Error += 1 print 'Error reading', Error time.sleep(2) # tri des listes listtemp = sorted(listtemp) listhum = sorted(listhum) print listtemp, listhum # suppression des valeurs extremes # del listtemp[14]
def read_data(self): humidity, temperature = Adafruit_DHT.read(self.sensor, self.pin) if humidity and temperature: self.humidity = humidity self.temperature = temperature