def dht_factory(gpio_pin: int): """ Given a GPIO pin, this function returns a DHT device instance, provided the requested pin is one of the pins listed below. We disallow certain pins to prevent conflicts with SPI and I2C interfaces. """ board_pins = { 4: board.D4, 17: board.D17, 27: board.D27, 22: board.D22, 5: board.D5, 6: board.D6, 7: board.D7, 13: board.D13, 19: board.D19, 26: board.D26, 23: board.D23, 24: board.D24, 25: board.D25, 12: board.D12, 16: board.D16, 20: board.D20, 21: board.D21 } if gpio_pin in board_pins.keys(): return adafruit_dht.DHT11(board_pins[gpio_pin]) else: raise RuntimeError( f"Failed to create DHT11 device - GPIO pin {gpio_pin} is invalid")
def __init__(self): self.PIN = D2 self.dhtDevice = adafruit_dht.DHT11(self.PIN, use_pulseio=False) try: self.value = self.dhtDevice.temperature except: self.value = 28
def read(data_pin, temp_format='f'): """read ambient sensor Required: data_pin (int): pin data is on temp_format (str, default=f): c or f """ if isinstance(data_pin, str) and data_pin == 'Empty': _eval_str = 'board.Empty' elif isinstance(data_pin, int): _eval_str = 'board.D' + str(data_pin) elif isinstance(data_pin, str): _eval_str = 'board.D' + data_pin else: return "Data pin supplied is not a valid value", str(data_pin) try: data_pin = eval(_eval_str) except AttributeError as error: return "Data pin not found", str(data_pin) dht_device = adafruit_dht.DHT11(data_pin) try: # by default the device returns c temperature = dht_device.temperature if temp_format == 'f': temperature = temperature * (9 / 5) + 32 humidity = dht_device.humidity return temperature, humidity except RuntimeError as error: # TODO: figure out better error handling and message return # print('Errors happen fairly often, DHT''s are hard to read, just keep going after you read the following error msg:') # print(error.args[0]) return "DHT read error", error.args[0]
def rasp_variables(self): self.pulsos = 0 self.tanque_lleno = 0 # inputs self.temp_dht_inicial = 0 # outputs self.s1 = [0, 1] self.s2 = [1, 1] self.be = [5, 1] self.bs = [6, 1] self.ven = [13, 1] self.voltaje = (20) self.outputs = (0, 1, 5, 6, 13) self.humidity_dht_inicial = 0 self.dhtDevice = adafruit_dht.DHT11(board.D16) self.sensor_flujo = 23 self.ml = 0 self.flotador = 12 GPIO.setmode(GPIO.BCM) GPIO.setup(self.sensor_flujo, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.sensor_flujo, GPIO.RISING) GPIO.add_event_callback(self.sensor_flujo, self.count_pulses) GPIO.setup(self.flotador, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.outputs, GPIO.OUT) GPIO.setup(self.voltaje, GPIO.OUT) self.pin_on(self.outputs, 1) self.pin_on(self.voltaje, 1)
def rngGrabber( ): # calculates RNG value with the output of the humidity/temperature sensor # Initial the dht device, with data pin connected to: dhtDevice = adafruit_dht.DHT11(board.D18) # you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio. # This may be necessary on a Linux single board computer like the Raspberry Pi, # but it will not work in CircuitPython. # dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) validInput = True while (validInput): try: # Print the values to the serial port num1 = random.randrange(1000) num2 = random.randrange(100) temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity validInput = False # print( # "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( # temperature_f, temperature_c, humidity # ) # ) dhtDevice.exit() return (((temperature_f + humidity) * num1) + num2) except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) time.sleep(2.0) continue except Exception as error: dhtDevice.exit() raise error time.sleep(2.0)
def record(): soil_sensor = MCP3008(0) light_sensor = MCP3008(1) air_sensor = adafruit_dht.DHT11(board.D18) try: air_temp_c = air_sensor.temperature air_humidity = air_sensor.humidity soil_humidity = round(soil_sensor.value, 2) light = round(abs(light_sensor.value - 1), 2) click.echo('-' * 20) click.echo(datetime.now().isoformat()) click.echo('Writing measures...') db.session.add(Measure(label='air-temp-c', value=air_temp_c)) db.session.add(Measure(label='air-humidity', value=air_humidity)) db.session.add(Measure(label='soil-humidity', value=soil_humidity)) db.session.add(Measure(label='light', value=light)) db.session.commit() click.echo('Wrote 4 measures.') except RuntimeError as err: click.echo(err)
def main(): log = LoggerUtility.get_logger("dht11.log") log.info("**************************** START ****************************") # Initial the dht device, with data pin connected to: log.info("Initializing the device DHT11 on pin 18...") dhtDevice = adafruit_dht.DHT11(board.D18) # ----------------------------------------------------------------------- # # initialize your data store # ----------------------------------------------------------------------- # log.info("Setting up data block and context...") block = ModbusDHTDataBlock(dhtDevice, log) # block = ModbusSequentialDataBlock(0, [3]*5) # print(block.getValues(0,2)) store = {0x01: ModbusSlaveContext(di=block, co=block, hr=block, ir=block)} context = ModbusServerContext(slaves=store, single=False) # ----------------------------------------------------------------------- # # initialize the server information # ----------------------------------------------------------------------- # log.info("Getting identity...") identity = ModbusUtility.get_modbus_device_identification("DHT11 Server") # ----------------------------------------------------------------------- # # run the TCP Server # ----------------------------------------------------------------------- # log.info("Starting TCP Server...") StartTcpServer(context, identity=identity, address=("0.0.0.0", 5000))
def main(): global api_address, dht_device signal.signal(signal.SIGINT, signal_handler) parser = argparse.ArgumentParser() parser.add_argument("--config", default='config/config.json', help="Config file location") args = parser.parse_args() with open(args.config) as json_data_file: config_data = json.load(json_data_file) api_address = config_data['api_address'] if api_address is None or api_address == '': print("API address invalid!") exit(1) print('Using API address: {}'.format(api_address)) sensor_id = get_serial_no() r = get_api_params() data = r.json() sleep_interval = data['post_frequency'] if not sleep_interval or sleep_interval == 0: # Make sure to have some amount of sleeping always so failures don't run away. sleep_interval = 1 print("Params from mother ship: {}".format(json.dumps(data, indent=2))) while True: humidity = None temperature_c = None temperature_f = None if dht_device is None: dht_device = adafruit_dht.DHT11(DHT_PIN) try: temperature_c = dht_device.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dht_device.humidity except RuntimeError as e: print("RuntimeError collecting from sensor: {}".format(e.args[0])) except Exception as e: dht_device.exit() dht_device = None print("Unexpected error collecting from sensor: {}".format(e)) if humidity is not None and temperature_c is not None and temperature_f is not None: print("Temp={:0.2f}C ({:0.2f}F) Humidity={:0.2f}%".format( temperature_c, temperature_f, humidity)) send_data(sensor_id, temperature_f, humidity) time.sleep(sleep_interval)
def get_temp_hum(pin): global humidity, temperature temp_sensor = adafruit_dht.DHT11(pin) while True: temperature = temp_sensor.temperature humidity = temp_sensor.humidity #humidity, temperature = Adafruit_DHT.read_retry(sensor=temp_sensor, pin = pin, delay_seconds=1) print(humidity, " ", temperature) time.sleep(1)
class dht11: _sensor = adafruit_dht.DHT11(board.GPIO14) @classmethod def get_reading(cls): return { "tempature": cls._sensor.temperature, "humidity": cls._sensor.humidity, }
def __init__(self, sensor: SensorInfo, pin: any, retries: int): self.sensorInfo = sensor self.pin = pin self.retries = retries if sensor.model == MODEL_DHT22: self.dht_device = adafruit_dht.DHT22(pin, use_pulseio=False) elif sensor.model == MODEL_DHT11: self.dht_device = adafruit_dht.DHT11(pin, use_pulseio=False) else: raise
def __init__(self, board_pin, sensor_type): if sensor_type == 'DHT11': self.dht = adafruit_dht.DHT11(board_pin) elif sensor_type == 'DHT22': self.dht = adafruit_dht.DHT22(board_pin) else: sys.exit('Invalid DHT sensor code: {}'.format(sensor_type)) self.last_T = 0 self.last_RH = 0
def __init__(self, pin, type='11'): """ :param pin: The pin number (in BCM) of the DHT data line. :type pin: int """ import adafruit_dht if (type == '11'): self.dht = adafruit_dht.DHT11(pin) else: self.dht = adafruit_dht.DHT22(pin)
def temperature_read(): try: sensor = adafruit_dht.DHT11( board.D16) # call library for DHT11 temperature sensor temperature = sensor.temperature # read in temperature and humidity temperaturebutton.config(text=str(temperature)) except RuntimeError as e: print('temp error {}'.format(e.args))
def read_sensor(pin, sensor_type, sensor_value): try: if int(sys.argv[1]) == 11: DHT_SENSOR = adafruit_dht.DHT11(pin) if int(sys.argv[1]) == 22: DHT_SENSOR = adafruit_dht.DHT22(pin) if sensor_value == 1: return (DHT_SENSOR.temperature) if sensor_value == 2: return (DHT_SENSOR.humidity) except RuntimeError as error: pass
def __init__(self): self.dht_device = adafruit_dht.DHT11(D4) self.is_mic_plugged = True if (self.is_mic_plugged): self.audio = pyaudio.PyAudio() self.stream = self.audio.open(format=pyaudio.paInt16, channels=1, rate=48000, input=True, frames_per_buffer=4800) self.stream.stop_stream()
def read_sensor(config): dhtDevice = adafruit_dht.DHT11(config["DHT11_PIN"]) measurements = config["MEASUREMENTS"] measurements["timestamp"] = datetime.now().timestamp() measurements["station_id"] = config["STATION_ID"] try: measurements["temperature_C"] = dhtDevice.temperature measurements["humidity_percent"] = dhtDevice.humidity except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) return measurements
def __init__(self, duration, freq): #Save the input parameters in variables self.duration = duration self.freq = freq #Print the current input parameters print(f'Duration= {duration}, Freq= {freq}') #If True it will print the value of temp and humi at each iteration self.debug = True #Create and instance of the DHT11 sensor, using D4 as input pin self.dht_device = adafruit_dht.DHT11(D4)
def __init__(self): self.__temp = 0 self.__door = False self.__sensorThread = threading.Thread self.__brightness = 0 self.__humidity = 0 self.isRaspberryPi = False if platform == 'linux': #checks if running an arm linux computer (Like rasppi), a better verification is needed if "arm" in os.uname().machine: self.isRaspberryPi = True self.__thermometer = adafruit_dht.DHT11(board.D4) self.__startSensorThread() self.arduinoConnect = False
def __init__(self): """ Object constructor for the sensors and actuators to be attached to it. """ self.client = None self.sensors = set() self.actuators = set() self.dhtDevice = adafruit_dht.DHT11( 18) # DHT init GPIO 18 (Physical 12) # if none, scan network for brokers and connect to identified broker. # scan with utils.find_broker() self.config_broker() utils.gpio_init()
def __init__(self, type=sensorType.DHT22, pin=None): if type == sensorType.DHT11 or type == sensorType.DHT22: self.type = type else: self.type = None self.pin = pin self.temperature_c = -999 if self.type == sensorType.DHT22 and self.pin is not None: self.dhtDevice = adafruit_dht.DHT22(self.pin) elif self.type == sensorType.DHT11 and self.pin is not None: self.dhtDevice = adafruit_dht.DHT11(self.pin) else: self.dhtDevice = None
def run(self): sensor = adafruit_dht.DHT11(board.D16) # setup dht11 to be read while self.go: try: interface.temperature_queue = sensor.temperature # read in temperature except: logging.error('Temperature Sensor Error') print('Temp Read Error') if interface.temperature_queue <= 0: time.sleep(1) # send new temperature every 1 seconds else: time.sleep(10)
def get_dht_data(): for proc in psutil.process_iter(): if proc.name() == 'libgpiod_pulsein' or proc.name() == 'libgpiod_pulsei': proc.kill() sensor = adafruit_dht.DHT11(board.D23) try: temp = sensor.temperature hum = sensor.humidity if temp is not None and hum is not None: return temp, hum except RuntimeError as err: print('1', err.args[0]) return None, None except Exception as err: sensor.exit() raise ('2', err)
def getRoomTemperature(seconds=5, pin=26): t_end = time.time() + seconds dhtDevice = adafruit_dht.DHT11(pin) while (time.time() < t_end): try: temp_f = dhtDevice.temperature * (9 / 5) + 32 humidity = dhtDevice.humidity dhtDevice.exit() return temp_f, humidity except RuntimeError as error: #error reading device (common) retry after 2 seconds print(error.args[0]) time.sleep(2.0) continue except Exception as error: dhtDevice.exit() raise error dhtDevice.exit()
def readAndSend(self): #login details passed to SetUp class. dht output set to gpio 24 newSetUp = SetUp(adafruit_dht.DHT11(board.D24), "Ddoy", "aio_OqZD42C9OM09r2wiYNAVoyK1K9yC", Client("Ddoy", "aio_OqZD42C9OM09r2wiYNAVoyK1K9yC")) #feeds passed to SetFeed class newFeed = SetFeed(newSetUp.aio.feeds('temperature'), newSetUp.aio.feeds('humidity'), newSetUp.aio.feeds('light')) #setting up adc spi communication with raspberry pi spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) #setting adc output to gpio 22 on pi cs = digitalio.DigitalInOut(board.D22) mcp = MCP.MCP3008(spi, cs) #setting LDR analog output to mcp3008 pin 1 chan1 = AnalogIn(mcp, MCP.P1) #while loop reads and sends sensor values every 0.5 sec, also handles errors while True: try: #getting values of DHT11 and ACD temperature = newSetUp.dhtDevice.temperature humidity = newSetUp.dhtDevice.humidity #voltage value converted to lumen light = chan1.voltage * 40 #prints light, temp and humidity to console print("Light level: " + str(light) + " lux") print("Temp: " + str(temperature) + "C " + "Humidity: " + str(humidity) + "%") #sends sensor values to feeds on webclient newSetUp.aio.send(newFeed.temperature_feed.key, str(temperature)) newSetUp.aio.send(newFeed.humidity_feed.key, str(humidity)) newSetUp.aio.send(newFeed.light_feed.key, str(light)) #displays error causing runtime then continues while loop except RuntimeError as error: print(error.args[0]) time.sleep(0.5) continue except Exception as error: raise error #closes program when keyboard interrupted except (KeyboardInterrupt, SystemExit): interrupt() time.sleep(0.5)
def get_dht_data(**kwargs): verbose = kwargs['verbose'] read_interval = kwargs['DHT_read_interval'] dht_type = kwargs['DHT_type'] pin = kwargs['DHT_pin'] import adafruit_dht from time import sleep debug = "yes" delay = 0 dht_device = adafruit_dht.DHT22(pin) if dht_type == "DHT11": dht_device = adafruit_dht.DHT11(pin) while True: try: temperature = dht_device.temperature humidity = dht_device.humidity redis_db.mset({ 'DHT_Humidity': humidity, 'DHT_Temperature': temperature, }) redis_db.expire('DHT_Humidity', read_interval * 2) redis_db.expire('DHT_Temperature', read_interval * 2) if bool(verbose) is True: print(dht_type + " Temperature: {:.1f}°C ".format(temperature)) print(dht_type + " Humidity: {}% ".format(humidity)) print('') delay -= 1 if delay < 0: delay = 0 except OverflowError as error: if debug is 'yes': print(f'Problem with DHT sensor: {error}') delay += 1 except RuntimeError as error: if debug is 'yes': print(f'Problem with DHT sensor - {error}') delay += 1 finally: if debug is 'yes': print(f'DHT delay: {delay}') redis_db.set('DHT_delay', delay) sleep(read_interval + delay)
def meres(): global temp global hum dht_device = adafruit_dht.DHT11(board.D4) mariadb_connection = mariadb.connect(user='******', password='******', database='data') cursor = mariadb_connection.cursor() while True: temp = dht_device.temperature hum = dht_device.humidity cursor.execute("INSERT INTO `Hopara`(`Hofok`, `Para`) VALUES (%s,%s)", (temp, hum)) cursor.execute( "DELETE FROM Hopara WHERE IDOPONT<DATE_SUB(LOCALTIME(), INTERVAL 3 HOUR)" ) mariadb_connection.commit() sleep(10)
def refreshSensor(thing): logger.log("Refreshing sensor values:", thing.name) if thing.thingClassId == dht11ThingClassId: gpio = thing.paramValue(dht11ThingRpiGpioParamTypeId) logger.log("GPIO pin:", gpio) dhtDevice = adafruit_dht.DHT11(piPinMap[gpio], use_pulseio=False) thing.setStateValue(dht11TemperatureStateTypeId, dhtDevice.temperature) thing.setStateValue(dht11HumidityStateTypeId, dhtDevice.humidity) elif thing.thingClassId == dht22ThingClassId: gpio = thing.paramValue(dht22ThingRpiGpioParamTypeId) logger.log("GPIO pin:", gpio) dhtDevice = adafruit_dht.DHT22(piPinMap[gpio], use_pulseio=False) thing.setStateValue(dht22TemperatureStateTypeId, dhtDevice.temperature) thing.setStateValue(dht22HumidityStateTypeId, dhtDevice.humidity) else: logger.crit("Unhandled thing class:", thing.thingClassId)
def __init__(self, gpio_relay, gpio_flow, ip_address=None, humid_temp="DHT22", moisture="I2C"): IotDevice.__init__(self) if gpio_relay == "SIM": self.gpio_relay = None else: if ip_address is not None: self.gpio_relay = LED(gpio_relay, PiGPIOFactory(host=ip_address)) else: self.gpio_relay = LED(gpio_relay) # For now we want to leave the DHT sensor (measures temperature and humidity) # connected to pin 18. if humid_temp == "BME280": i2c = board.I2C() self.ht_sensor = Bme280(i2c) self.ht_sensor.set_sea_level_pressure(1022.2) elif humid_temp == "DHT11": self.ht_sensor = adafruit_dht.DHT11(board.D18) elif humid_temp == "DHT22": self.ht_sensor = adafruit_dht.DHT22(board.D18) else: self.ht_sensor = None # For now we want to leave SCL to pin 3 and SDA to pin 2 for i2c interface. # meaning moisture sensor will need to be connected to these pins if moisture == "SIM": self.moisture_sensor = None else: self.moisture_sensor = Seesaw(busio.I2C(board.D3, board.D2), addr=0x36) if gpio_flow == "SIM": self.gpio_flow = None else: self.gpio_flow = FrequencySignal(gpio_flow)
def readAmbient(data_pin): if isinstance(data_pin, str) and data_pin == 'Empty': data_pin = eval('board.Empty') elif isinstance(data_pin, int): data_pin = eval('board.D' + str(data_pin)) elif isinstance(data_pin, str): data_pin = eval('board.D' + data_pin) else: return "Data pin supplied is not a valid value", str(data_pin) dht_device = adafruit_dht.DHT11(data_pin) try: temperature_c = dht_device.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dht_device.humidity return temperature_f, humidity except RuntimeError as error: # TODO: figure out better error handling and message return # print('Errors happen fairly often, DHT''s are hard to read, just keep going after you read the following error msg:') # print(error.args[0]) return "DHT read error", error.args[0]