def dht_init(gpio): """ Initialize the DHT22 sensor and return it :param int gpio: The GPIO BCM pin number where the sensor is attached :return dht_sensor: The initialized dht_sensor object :return df: The initialized DataFrame """ try: # Create pandas DataFrame df = pd.DataFrame(columns=columns) # Set the dtype of the time column to datetime64[ns] to have an interchangeable unit df['date'] = pd.to_datetime(df['date']) df['time'] = pd.to_datetime(df['time']) # Create the DHT22 object with the corresponding GPIO pin number dht_sensor = DHT22(gpio) # Create a CSV file with given columns names with open(csv_path, 'w', newline='') as file: writer = csv.writer( file, delimiter=' ') # The separator is a single space writer.writerow(columns) # Write the header row file.close() print("DHT22 sensor initialized.") return dht_sensor, df # Return the sensor object and the empty dataframe except: print("DHT22 sensor could not be initialized.")
def capture_dht22_data(connection_id): """ Capture data from sensor and save it in database select sensors from database get data based on PIN ID :return: """ sql = "SELECT id, dht22_pin from sensors WHERE sensor_type = 'DHT22' ORDER BY id" cur = connection_id.cursor() try: cur.execute(sql) rows = cur.fetchall() pitemp = pigpio.pi('pitemp') sensors = [] ids = [] i = 0 for row in rows: ids.append(row[0]) # noinspection PyTypeChecker sensors.append(DHT22(row[1], timeout_secs=5, pi=pitemp)) i = i + 1 while True: cur_date = time.strftime('%Y-%m-%d') cur_time = time.strftime('%H:%M') results = [] for sensor in range(0, len(sensors)): try: result = sensors[sensor].sample(samples=5, max_retries=5) results.append(result) # as we are reading multiple sensors, introduce a little sleep between the readings. # this seems to cut down on the number of timeouts and False status values. time.sleep(2) except TimeoutError: print("Timout on sensor " + str(sensor)) # Create some dummy values for logging purposes results.append({ 'temp_c': 0, 'temp_f': 0, 'humidity': 0, 'valid': False }) log_data(connection_id, ids[sensor], 0, 0, None, cur_date, cur_time) else: print(result) log_data(connection_id, ids[sensor], result['humidity'], result['temp_c'], None, cur_date, cur_time) pass prometheus_log(results) time.sleep(120) except Error as error: print(error)
def _load_hardware(self): address = self._address if len(address) >= 2 and terrariumUtils.is_float(address[1]): # Set / enable power management self._device['power_mngt'] = terrariumUtils.to_BCM_port_number(address[1]) if self.HARDWARE == terrariumDHT11Sensor.HARDWARE: device = DHT11(terrariumUtils.to_BCM_port_number(address[0])) elif self.HARDWARE in [terrariumDHT22Sensor.HARDWARE, terrariumAM2302Sensor.HARDWARE]: device = DHT22(terrariumUtils.to_BCM_port_number(address[0])) return device
def test_dht22(dht22gpio): if not dht22gpio: pytest.skip("Skipping. No GPIO Pin for DHT22 Provided.") return dht = DHT22(gpio=int(dht22gpio)) result = dht.read() print(result) dht22_result = result assert 'temp_c' in result assert 'temp_f' in result assert 'humidity' in result assert 'valid' in result assert 0 <= result['humidity'] <= 100
def test_dht22_data_parsing(): #data22 = [0b00000010, 0b10010010, 0b00000001, 0b00001101, 0b10100010] data22 = [ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0 ] GPIO = 21 # GPIO for constructor, but never queried. dht = DHT22(gpio=GPIO) dht.data = data22 result = dht._parse_data() print(result) assert result['temp_c'] == 26.9 assert result['temp_f'] == 80.4 assert result['humidity'] == 65.8 assert result['valid'] == True
def test_dht22_data_parsing_fail_checksum(): #data22 = [0b00000010, 0b10010010, 0b00000001, 0b00001101, 0b10101111] data22 = [ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1 ] GPIO = 21 # GPIO for constructor, but never queried. dht = DHT22(gpio=GPIO) dht.data = data22 result = dht._parse_data() print(result) assert result['temp_c'] == 0 assert result['temp_f'] == 0 assert result['humidity'] == 0 assert result['valid'] == False
from pigpio_dht import DHT22 # IMPORTANT: run "sudo pigpiod" to run the daemon for the sensor gpio = 4 # BCM Numbering sensor = DHT22(gpio) result = sensor.sample(samples=5) print(result)
if not WRITE_API_KEY or not CHANNEL_ID: print("\nCONFIGURATION REQUIRED\nPlease update {} and add your ThingSpeak WRITE_API_KEY and CHANNEL_ID\n".format(__file__)) quit(1) HOST = "mqtt.thingspeak.com" MQTT_TOPIC = "channels/" + CHANNEL_ID + "/publish/" + WRITE_API_KEY QOS = 0 # ThinkSpeak API indicates MATT QoS is to be 0 # How often we collect and send data to ThingSpeak POLL_INTERVAL_SECS = 60*10 # 10 Minutes #dht = DHT11(GPIO, use_internal_pullup=True, timeout_secs=0.5) dht = DHT22(GPIO, use_internal_pullup=True, timeout_secs=0.5) if __name__ == "__main__": logger.info("Collecting Data and Sending to ThingSpeak every {} seconds. Press Control + C to Exit".format(POLL_INTERVAL_SECS)) try: while True: timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') try: result = dht.read(retries=5) # Singe data read (faster) #result = dht.sample() # Multiple data reads, then take mean (slower) except Exception as e: # Failed to get reading from sensor
'Co2': 17, 'Fertilizer': 27, 'Water Conditioner': 22 } for (p_type, pin) in pumps.items(): GPIO.setup(pin, GPIO.OUT) Button = 16 # Initializing the GPIO pin 16 for Button led_pin = 12 # Initializing the GPIO pin 12 for LED FLASH = 0 # Initializing LED States PULSE = 1 # Initializing LED States dht_pin = 22 # DHT22 Sensor pin sensor_dht = DHT22.DHT22(dht_pin) GPIO.setup(Button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Setup Button GPIO.setup(led_pin, GPIO.OUT) # Notification LED pin pwm = GPIO.PWM(led_pin, 100) # Created a PWM object pwm.start(0) # Started PWM at 0% duty cycle except ModuleNotFoundError: print("No Rpi Module Found") class CalibrationCancelled(Exception): pass class Hardware: def __init__(self):
def relayOFF(gpioNumber): GPIO.output(gpioNumber, GPIO.LOW) relayStatus = False return relayStatus def waitXSeconds(n): time.sleep(n) for i in range (0,n): print(i) try: gpioSetup() relayStatus = False while True: sensor = DHT22(17) result = sensor.read() timeStamp = time.ctime() resultHumidity = result.get('humidity') resultValidation = result.get('valid') if resultValidation == False: time.sleep (2) #If sensor is not meausuring properly, then program sleeps for 2 sec else: if resultHumidity < 80: relayStatus = relayON(27, relayStatus) print(relayStatus) waitXSeconds(10) print('case1') print(result, timeStamp) elif resultHumidity > 85: waitXSeconds(10)
#!/usr/bin/env python import paho.mqtt.client as paho # pip install paho-mqtt import time import logging import sys from pigpio_dht import DHT22 MQTT_PREFIX = 'rpi' BROKER_HOST = 'rpi3.kleber' BROKER_PORT = 1883 FREQUENCY_S = 300 dhtDevice = DHT22(4) def data(retry=True): values = {} try: result = dhtDevice.read() if result['valid']: values['waschkueche/temp'] = result['temp_c'] values['waschkueche/humidity'] = result['humidity'] logging.info("{:.1f} C, {}% ".format(values['waschkueche/temp'], values['waschkueche/humidity'])) else: logging.info("data not valid")
def __init__( self, gpio, samples ): self.gpio = gpio self.samples = samples self.sensor = DHT22( gpio )