def _check_refresh(self, min_refresh_rate): now = ticks_ms() if self.last_measure == 0 or now - self.last_measure > min_refresh_rate: try: DHT22.measure(self) except OSError: raise OSError( "Please check if sensor is connected to Port {0}".format( self.port)) self.last_measure = now
def __init__( self, pin, precision_temp=2, precision_humid=1, # extend or shrink according to your sensor offset_temp=0, offset_humid=0, # also here interval=None, mqtt_topic=None): interval = interval or config.INTERVAL_SEND_SENSOR self.topic = mqtt_topic or mqtt.getDeviceTopic(component_name) ############################## # adapt to your sensor by extending/removing unneeded values like in the constructor arguments self._prec_temp = int(precision_temp) self._prec_humid = int(precision_humid) ### self._offs_temp = float(offset_temp) self._offs_humid = float(offset_humid) ############################## # create sensor object if type(pin) == str: pin = config.pins[pin] self.sensor = Sensor( machine.Pin(pin)) # add neccessary constructor arguments here ############################## # choose a background loop that periodically reads the values and publishes it # (function is created below) background_loop = self.tempHumid ############################## gc.collect() asyncio.get_event_loop().create_task( self._loop(background_loop, interval))
def __init__(self, pin, precision_temp=2, precision_humid=1, offset_temp=0, offset_humid=0, friendly_name_temp=None, friendly_name_humid=None, **kwargs): # This makes it possible to use multiple instances of MySensor and have unique identifier global _unit_index _unit_index += 1 super().__init__(COMPONENT_NAME, __version__, _unit_index, logger=_log, **kwargs) self._addSensorType(SENSOR_TEMPERATURE, precision_temp, offset_temp, _VAL_T_TEMPERATURE, "°C", friendly_name_temp) self._addSensorType(SENSOR_HUMIDITY, precision_humid, offset_humid, _VAL_T_HUMIDITY, "%", friendly_name_humid) ############################## # create sensor object self.sensor = Sensor( Pin(pin)) # add neccessary constructor arguments here ############################## gc.collect()
def __init__(self, pin, precision_temp=2, precision_humid=1, offset_temp=0, offset_humid=0, interval_publish=None, interval_reading=None, mqtt_topic=None, friendly_name_temp=None, friendly_name_humid=None, discover=True, expose_intervals=False, intervals_topic=None): # This makes it possible to use multiple instances of MySensor and have unique identifier global _unit_index _unit_index += 1 super().__init__(COMPONENT_NAME, __version__, _unit_index, discover, interval_publish, interval_reading, mqtt_topic, _log, expose_intervals, intervals_topic) self._addSensorType(SENSOR_TEMPERATURE, precision_temp, offset_temp, _VAL_T_TEMPERATURE, "°C", friendly_name_temp) self._addSensorType(SENSOR_HUMIDITY, precision_humid, offset_humid, _VAL_T_HUMIDITY, "%", friendly_name_humid) ############################## # create sensor object self.sensor = Sensor( Pin(pin)) # add neccessary constructor arguments here ############################## gc.collect()
def run(): connect_to_wifi() d = DHT22(Pin(PIN_LABEL["D5"])) while True: d.measure() send_data(d.temperature(), d.humidity()) time.sleep(1)
def __init_DHT22(): global __DHT_OBJ if __DHT_OBJ is None: from dht import DHT22 from machine import Pin __DHT_OBJ = DHT22(Pin(physical_pin('dhtpin'))) return __DHT_OBJ
def __init__( self, pin, precision_temp=2, precision_humid=1, # extend or shrink according to your sensor offset_temp=0, offset_humid=0, # also here interval=None, mqtt_topic=None, friendly_name=None): super().__init__() self._interval = interval or config.INTERVAL_SEND_SENSOR self._topic = mqtt_topic or _mqtt.getDeviceTopic(_component_name) ############################## # adapt to your sensor by extending/removing unneeded values like in the constructor arguments self._prec_temp = int(precision_temp) self._prec_humid = int(precision_humid) ### self._offs_temp = float(offset_temp) self._offs_humid = float(offset_humid) ############################## # create sensor object self.sensor = Sensor( Pin(pin)) # add neccessary constructor arguments here ############################## global _count self._count = _count _count += 1 self._frn = friendly_name gc.collect()
def __init_DHT22(): global __DHT_OBJ if __DHT_OBJ is None: from dht import DHT22 from machine import Pin from LogicalPins import get_pin_on_platform_by_key __DHT_OBJ = DHT22(Pin(get_pin_on_platform_by_key('simple_1'))) return __DHT_OBJ
def __init__(self, pin): if not isinstance(pin, int): raise TypeError("pin must be integer") from dht import DHT22 self.sensor = DHT22(machine.Pin(pin)) time.sleep(1) # some delay to stabilize sensor self.t = None self.h = None
def get_reading(): dht_power_pin = Pin(config.DHT_POWER_PIN, Pin.OUT) dht_power_pin.on() dht = DHT22(Pin(config.DHT_DATA_PIN)) time.sleep(3) dht.measure() reading_time = time.time() + 946684800 dht_power_pin.off() return (reading_time, dht.temperature(), dht.humidity())
def setup(): # wifi name = config['wifi']['name'] passwd = config['wifi']['password'] connect_wifi(name, passwd) # sensors moisture_pin = ADC(config['board']['moisture_pin_num']) pin = Pin(config['board']['temp_humid_pin_num']) temp_humid_pin = DHT22(pin) return (moisture_pin, temp_humid_pin)
def read_dht22(): pin = 0 dht = DHT22(Pin(pin)) dht.measure() return [{ "id": "dht22_{}_temp".format(pin), "value": dht.temperature(), "type": "temperature" }, { "id": "dht22_{}_humidity".format(pin), "value": dht.humidity(), "type": "humidity" }]
class DHT22(ComponentSensor): def __init__(self, pin, precision_temp=2, precision_humid=1, offset_temp=0, offset_humid=0, interval_publish=None, interval_reading=None, mqtt_topic=None, friendly_name_temp=None, friendly_name_humid=None, discover=True, expose_intervals=False, intervals_topic=None): # This makes it possible to use multiple instances of MySensor and have unique identifier global _unit_index _unit_index += 1 super().__init__(COMPONENT_NAME, __version__, _unit_index, discover, interval_publish, interval_reading, mqtt_topic, _log, expose_intervals, intervals_topic) self._addSensorType(SENSOR_TEMPERATURE, precision_temp, offset_temp, _VAL_T_TEMPERATURE, "°C", friendly_name_temp) self._addSensorType(SENSOR_HUMIDITY, precision_humid, offset_humid, _VAL_T_HUMIDITY, "%", friendly_name_humid) ############################## # create sensor object self.sensor = Sensor( Pin(pin)) # add neccessary constructor arguments here ############################## gc.collect() async def _read(self): try: self.sensor.measure() await asyncio.sleep(1) self.sensor.measure() except Exception as e: await _log.asyncLog("error", "DHT22 is not working,", e, timeout=10) return None, None await asyncio.sleep_ms( 100 ) # give other tasks some time as measure() is slow and blocking try: temp = self.sensor.temperature() humid = self.sensor.humidity() except Exception as e: await _log.asyncLog("error", "Error reading DHT22:", e, timeout=10) else: await self._setValue(SENSOR_TEMPERATURE, temp) await self._setValue(SENSOR_HUMIDITY, humid)
def __init__(self, node_name, node_ip, node_gateway, node_wifi_ssid, node_wifi_password): self.node_name = node_name self.node_ip = node_ip self.node_gateway = node_gateway self.node_wifi_ssid = node_wifi_ssid self.node_wifi_password = node_wifi_password self.client = MQTTClient(self.node_name, self.node_gateway) self.client.connect() self.sensordht = DHT22(Pin(15, Pin.IN, Pin.PULL_UP)) self.i2c = I2C(scl=Pin(22), sda=Pin(21)) self.i2csgp30 = I2C(scl=Pin(17), sda=Pin(16)) self.bmp = bmp280.BMP280(self.i2c) self.sgp30 = adafruit_sgp30.Adafruit_SGP30(self.i2csgp30) self.sgp30.iaq_init() self.mq135 = mq135.MQ135(Pin(36)) self.data = {} self.data["node"] = self.node_name
def temp_hum(): client = MQTTClient(CLIENT_ID, SERVER) client.connect() sensor = DHT22(Pin(5, Pin.IN, Pin.PULL_UP)) while True: try: sensor.measure() temperature = sensor.temperature() humidity = sensor.humidity() if isinstance(temperature, float) and isinstance(humidity, float): msg = (b"{0:3.1f},{1:3.1f}".format(temperature, humidity)) print(msg) # to be removed later client.publish(TOPIC, msg) except OSError: print("System error") # sleep(3600) # one hour sleep(10) # for testing
def startSensing(): sensor = DHT22(Pin(cnf.DHT22_PIN, Pin.IN, Pin.PULL_UP)) ledPublish = None if cnf.LED_PUBLISH_PIN == None else Pin( cnf.LED_PUBLISH_PIN, Pin.OUT) ledRead = None if cnf.LED_READ_PIN == None else Pin( cnf.LED_READ_PIN, Pin.OUT) ledError = None if cnf.LED_ERROR_PIN == None else Pin( cnf.LED_ERROR_PIN, Pin.OUT) try: client = viv.initMQTTClient(cnf.MQTT_BROKER, cnf.CLIENT_ID) try: while True: try: if isinstance(ledRead, Pin): ledRead.value(1) readings = viv.readValues(sensor) print(readings) t, h = readings if isinstance(ledRead, Pin): ledRead.value(0) if isinstance(ledPublish, Pin): ledPublish.value(1) viv.publishValue(client, cnf.TOPIC_TEMP, t) viv.publishValue(client, cnf.TOPIC_HUMID, h) if isinstance(ledPublish, Pin): ledPublish.value(0) except OSError: print('Failed to read sensor') sleep(cnf.SENSOR_SLEEP) except KeyboardInterrupt: print("\nCtrl-C pressed. Cleaning up and exiting") finally: client.disconnect() if isinstance(ledPublish, Pin): ledPublish.value(0) if isinstance(ledRead, Pin): ledRead.value(0) except OSError: util.blink(ledError, 5, 2, 1, 1, 0.1) print('Could not connect to MQTT broker') sys.exit()
def __init__(self, **kwargs): super().__init__(**kwargs) self.temperature_id = None self.humidity_id = None self.add_id(self.sensor, kwargs.get('_id')) self._last_measure = None sensor_value = getattr(HumidityTemperatureSensor, self.pattern) if sensor_value == 0: from dht import DHT11 self.sensor = DHT11(Pin(self.pins[0], Pin.PULL_UP)) elif sensor_value == 1: from dht import DHT22 self.sensor = DHT22(Pin(self.pins[0], Pin.PULL_UP)) else: raise Exception('sensor not available') self._last_temperature = None self._last_humidity = None
def __init__(self): self.wifi = Wifi( ssid=CONFIG["WIFI_SSID"], password=CONFIG["WIFI_PASSWORD"], gmt=CONFIG["GMT"], ) self.mqtt = Mqtt( ip=CONFIG["MQTT_IP"], user=CONFIG["MQTT_USER"], password=CONFIG["MQTT_PASS"], keepalive=CONFIG["MQTT_KEEPALIVE"], ) self.mqtt.set_last_will( topic=CONFIG["LW_TOPIC"], msg=ujson.dumps(CONFIG["LW_MSG_OFFLINE"]), retain=CONFIG["LW_RETAIN"], qos=CONFIG["LW_QOS"], ) self.dht22 = DHT22(Pin(CONFIG["DHT22_PIN"])) self.is_sending_synchronizate = False
def publish(): SERVER = '192.168.0.13' # MQTT Server Address (Change to the IP address of you$ CLIENT_ID = 'ESP32_DHT22_Sensor' TOPIC = b'temp_humidity' client = MQTTClient(CLIENT_ID, SERVER) client.connect() # Connect to MQTT broker dht_running = True sensor = DHT22(Pin( 15, Pin.IN, Pin.PULL_UP)) #DHT22 on GPIO 15 (input with internal pull up resistor) while dht_running: try: sensor.measure() # Poll sensor t = sensor.temperature() h = sensor.humidity() tm = time.localtime(time.time()) tmstr = '{:04d}-{:02d}-{:02d} {:02d}:{:02d}'.format( tm[0], tm[1], tm[2], tm[3], tm[4]) print(tm) print(t, h, tm[0]) if isinstance(t, float) and isinstance( h, float ) and tm[0] > 2000: # Confirm sensor results are numeric msg = (b'{0},{1:3.1f},{2:3.1f}'.format(tmstr, t, h)) client.publish( TOPIC, msg, retain=True) # Publish sensor data to MQTT topic print(str(msg)) print('Sent to ' + SERVER + ' as ' + CLIENT_ID + '. Exiting.') client.disconnect() dht_running = False else: print('Invalid sensor readings.') except OSError: print('Failed to read sensor.') time.sleep(5)
# micropython GPIO wrapper to read data from sensor for ESP8266 based board
import picoweb from time import sleep from machine import Pin from dht import DHT22 import network sta_if = network.WLAN(network.STA_IF) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect('DangerVirus', 'abivarsh@2016') while not sta_if.isconnected(): pass print('network config:', sta_if.ifconfig()) ipadd = sta_if.ifconfig() app = picoweb.WebApp(__name__) hw_sensor = DHT22(Pin(13, Pin.IN, Pin.PULL_UP)) @app.route("/temp") def html(req, resp): hw_sensor.measure() t = hw_sensor.temperature() h = hw_sensor.humidity() sensor = {"tmpr": t, "hmdty": h} msg = (b'{0:3.1f} {1:3.1f}'.format(t, h)) print(msg) yield from picoweb.start_response(resp, content_type="text/html") yield from app.render_template(resp, "sensor.tpl", (sensor, )) app.run(debug=True, host=ipadd[0])
sda = Pin(21) pins = [ None, Pin(23, Pin.OUT), Pin(19, Pin.OUT), Pin(18, Pin.OUT), Pin(4, Pin.OUT) ] i2c = I2C(scl=scl, sda=sda, freq=100000) oled = SSD1306_I2C(128, 64, i2c, addr=0x3C) oled.fill(0) oled.text('ESP32', 45, 5) oled.text('MicroPython', 20, 20) oled.show() loop = asyncio.get_event_loop() d = DHT22(dthPn) def btn_callback(e): global client global CLIENT_ID topic = 'micro/{0}/alarm'.format(CLIENT_ID.decode("utf-8")) msg = None if e is btn1: msg = json.dumps({'type': 'room1', 'msg': 'alarm'}) else: msg = json.dumps({'type': 'room2', 'msg': 'alarm'}) client.publish(topic, msg)
from dht import DHT22 from machine import Pin import time dhtPn = Pin(17) dht = DHT22(dhtPn) while True: dht.measure() print('Temp: {0:.2f}, Humi: {1:.2f}'.format(dht.temperature(), dht.humidity())) time.sleep(5)
### misc ### from machine import Pin from time import sleep from time import sleep_ms from machine import deepsleep SLEEPDELAY = SLEEPTIME * 60000 - 3000 # in milliseconds; edit SLEEPTIME to modify ### network ### from network import WLAN from network import STA_IF station = WLAN(STA_IF) ### DHT22 ### from dht import DHT22 sensor = DHT22(Pin(15, Pin.IN, Pin.PULL_UP)) ### LED ### #from machine import Pin # ESP32 modules have blue, active-high LED on GPIO2 LED2 = Pin(2, Pin.OUT, value=0) ### ADC ### from machine import ADC adc = ADC(Pin(36)) #adc.atten(adc.ATTN_0DB) adc.atten(adc.ATTN_11DB) adc.width(adc.WIDTH_10BIT) ### RTC ### from machine import RTC
c.set_callback(sub_cb) c.connect() c.subscribe(topic) #print("Connected to %s, subscribed to %s topic" % (server, topic)) try: c.wait_msg() finally: c.disconnect() #---End MQTT Sending--- #---DHT22--- from dht import DHT22 ds = DHT22(Pin(16)) #DHT22 connected to GPIO16 def medirTemHum(): try: ds.measure() tem = ds.temperature() hum = ds.humidity() #ed.value(1) return (tem, hum) except Exception as e: #led.value(0) return (-1, -1) #---End DHT22---
class DHT22: def __init__( self, pin, precision_temp=2, precision_humid=1, # extend or shrink according to your sensor offset_temp=0, offset_humid=0, # also here interval=None, mqtt_topic=None): interval = interval or config.INTERVAL_SEND_SENSOR self.topic = mqtt_topic or mqtt.getDeviceTopic(component_name) ############################## # adapt to your sensor by extending/removing unneeded values like in the constructor arguments self._prec_temp = int(precision_temp) self._prec_humid = int(precision_humid) ### self._offs_temp = float(offset_temp) self._offs_humid = float(offset_humid) ############################## # create sensor object if type(pin) == str: pin = config.pins[pin] self.sensor = Sensor( machine.Pin(pin)) # add neccessary constructor arguments here ############################## # choose a background loop that periodically reads the values and publishes it # (function is created below) background_loop = self.tempHumid ############################## gc.collect() asyncio.get_event_loop().create_task( self._loop(background_loop, interval)) async def _loop(self, gen, interval): while True: await gen() await asyncio.sleep(interval) async def _dht_read(self): try: self.sensor.measure() await asyncio.sleep(1) self.sensor.measure() except Exception as e: log.error("DHT22 is not working, {!s}".format(e)) return None, None await asyncio.sleep_ms( 100 ) # give other tasks some time as measure() is slow and blocking try: temp = self.sensor.temperature() humid = self.sensor.humidity() except Exception as e: log.error("Error reading DHT22: {!s}".format(e)) return None, None return temp, humid async def _read(self, prec, offs, get_value_number=0, publish=True): if get_value_number > 2: log.error("DHT22 get_value_number can't be >2") return None try: values = await self._dht_read() except Exception as e: log.error("Error reading sensor {!s}: {!s}".format( component_name, e)) return None if values[0] is not None and values[1] is not None: for i in range(0, len(values)): try: values[i] = round(values[i], prec) except Exception as e: log.error("DHT22 can't round value: {!s}, {!s}".format( values[i], e)) return None if get_value_number != 0 else (None, None) values[i] += offs else: log.warn("Sensor {!s} got no value".format(component_name)) return None if get_value_number != 0 else (None, None) if publish: if get_value_number == 0: await mqtt.publish( self.topic, { "temperature": ("{0:." + str(self._prec_temp) + "f}").format( values[0]), "humidity": ("{0:." + str(self._prec_humid) + "f}").format( values[1]) }) # formating prevents values like 51.500000000001 on esp32_lobo else: await mqtt.publish(self.topic, ("{0:." + str(prec) + "f}").format( values[get_value_number])) return { "temperature": values[0], "humiditiy": values[1] } if get_value_number == 0 else values[get_value_number] ############################## # remove or add functions below depending on the values of your sensor async def temperature(self, publish=True): return await self._read(self._prec_temp, self._offs_temp, 1, publish) async def humidity(self, publish=True): return await self._read(self._prec_humid, self._offs_humid, 2, publish) async def tempHumid(self, publish=True): return await self._read(self._prec_humid, self._offs_humid, 0, publish)
# Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(topic) print("Connected to %s, subscribed to %s topic" % (server, topic)) try: c.wait_msg() finally: c.disconnect() #---End MQTT Sending--- #---DHT22--- from dht import DHT22 ds = DHT22(Pin(4)) #DHT22 connected to GPIO4 def medirTemHum(): try: ds.measure() tem = ds.temperature() hum = ds.humidity() #ed.value(1) return (tem,hum) except Exception as e: #led.value(0) return (-1,-1) #---End DHT22--- #---Main Program---
pin_sda = 21 pin_sens = 16 else: # ESP8266 pin_scl = 5 pin_sda = 4 pin_sens = 2 width = 64 height = 48 frequency = 100000 OP_SINGLE_HRES2 = 0x21 i2c = I2C(scl=Pin(pin_scl), sda=Pin(pin_sda), freq=frequency) oled = SSD1306_I2C(width, height, i2c) sensor_Pin = Pin(pin_sens, Pin.IN) sensor = DHT22(sensor_Pin) topic1 = b'TempDHT22-2' topic2 = b'HumidDHT22-2' topic3 = b'Light' client_id = hexlify(unique_id()) def connect_to_mqtt(config): global client_id client = MQTTClient(client_id, config['mqtt']['broker']) client.connect() print('Connected to %s MQTT broker' % (config['mqtt']['broker'])) return client def restart_and_reconnect(): print('Failed to connect to MQTT broker. Reconnecting...') sleep(10)
from umqtt import MQTTClient import machine, ubinascii import time, gc import network import json, errno from dht import DHT22 from machine import Pin, I2C, Timer, ADC from ssd1306 import SSD1306_I2C import _thread as th a1 = ADC(Pin(32)) a2 = ADC(Pin(33)) a3 = ADC(Pin(34)) scl = Pin(22) sda = Pin(21) i2c = I2C(scl=scl, sda=sda, freq=100000) oled = SSD1306_I2C(128, 64, i2c) oled.fill(0) oled.text('ESP32', 45, 5) oled.text('MicroPython', 20, 20) oled.text('System Startimg', 3, 35) oled.show() dhtPn = Pin(17) d = DHT22(dhtPn) tim0 = Timer(0) wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect('see_dum', '0863219053') while not wlan.isconnected(): print('Wait connection') time.sleep(1)
import ssd1306 from machine import I2C, Pin from dht import DHT22 from time import sleep i2c = I2C(-1, Pin(5), Pin(4)) oled = ssd1306.SSD1306_I2C(64, 48, i2c) dht = DHT22(Pin(2)) def measure_realtime(): dht.measure() sleep(0.2) dht.measure() def term1(): oled.fill(0) oled.invert(0) oled.text("GDG Bolu", 0,0) oled.text("Sicak", 0,10) oled.text("Kanlisin", 0,20) oled.text(":)", 0, 30) oled.show() kontrol = False def term2(): global kontrol oled.fill(0)