def main_client(addr): nic = network.WIZNET5K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4) nic.ifconfig((SENSOR_IP, SENSOR_MASK, SENSOR_GATEWAY, SENSOR_DNS)) # print(nic.ifconfig()) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) count = 0 try: s.connect(addr) except: pass data = { 'serial_no':'1234567890', 'ip':SENSOR_IP, 'op':gOperator['OP_REGISTER'], 'type':gSensorType['TEMPERATURE'] } DHT22.init() while True: pyb.delay(100) hum, tem = measure() print('%d hum:%f, tem:%f' % (count,hum, tem)) data['value'] = {'hum':hum, 'tem':tem} count += 1 try: send(s, 'post', '/test_pymagic', data) print(s.recv(4096)) except: pass pyb.delay(1000)
def getCalculatedData(): temperatureList = [] humidityList = [] pi = pigpio.pi() s = DHT22.sensor(pi, 18, LED=16, power=8) for i in range(1, measuresCount): s.trigger() time.sleep(0.2) humidity = s.humidity() temperature = s.temperature() temperatureList.append(temperature) humidityList.append(humidity) time.sleep(timeBetweenMeasures) averageTemperature = 0 if len(temperatureList) > 0: averageTemperature = averageValue(temperatureList) averageHumidity = 0 if len(humidityList) > 0: averageHumidity = averageValue(humidityList) return {"temperature": averageTemperature, "humidity": averageHumidity}
def integrated(): global schedule_str global weather_str global mise_str global U_arrive_str global D_arrive_str global now_temp ip_parser() weather_status = weather_parse() mise_status = mise_parse() metro_parse() scheduleRows = smdb.getSchedule() schedule_str = "Schedule Time : " + str( scheduleRows[0]['schedule_time']) + "Subject : " + str( scheduleRows[0]['subject']) weather_str = "Weather : " + weather_status mise_str = "Fine Dust : " + mise_status U_arrive_str = now_arrive_U D_arrive_str = now_arrive_D tempData = smdb.getTemp() min_temp = tempData[0]['min_temp'] max_temp = tempData[0]['max_temp'] now_temp = DHT22.getNowTemp() if now_temp > max_temp: # 에어컨 켜기 os.system("irsend SEND_ONCE whisen UN-JEON/JEONG-JI_18") elif now_temp < min_temp: # 에어컨 끄기 os.system("irsend SEND_ONCE whisen UN-JEON/JEONG-JI_OFF") time.sleep(60)
def temphum(): import pigpio from time import sleep import RPi.GPIO as GPIO pi = pigpio.pi() import DHT22 datapin = 4 s = DHT22.sensor(pi, datapin) s.trigger() sleep(2) t = s.humidity() h = s.temperature() #read soil moisture sensor GPIO.setmode(GPIO.BCM) # set up BCM GPIO numbering GPIO.setup(18, GPIO.IN) # this will carry on until you hit CTRL+C if GPIO.input(18): m = "Soil is DRY" print("no water detected") else: print("water detected") m = "Soil is WET" #print(t,s) print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)) s.cancel pi.stop() return (t, h, m)
def DHT_Run(self): #온습도 확인 INTERVAL = 3 pi = pigpio.pi() s = DHT22.sensor(pi, self.DHT_BCM) r = 0 next_reading = time.time() while True: r += 1 s.trigger() time.sleep(0.2) h = s.humidity() t = s.temperature() next_reading += INTERVAL time.sleep(next_reading - time.time()) if h > -100 and t > -100: break #elif h == -999 and t == -999: #print("DHT - 센서 핀 연결확인") s.cancel() pi.stop() return s.humidity(), s.temperature() #Info.py 테스트 #if __name__ == "__main__": # I = Info(Observer) # print(I.processRequest("INFO")) # while True: # print(I.Info_Lock) # print(I.detectEnvironment())
def read(pin): s = DHT22.sensor(pi, pin) s.trigger() sleep(1) # Necessary on faster Raspberry Pi's print('humidity: {:3.2f}'.format(s.humidity() / 1.)) print('temperature: {:3.2f}'.format(s.temperature() / 1.)) s.cancel()
def DHT22_Thread_Function(): while True: try: DHT22.Probe_Humidity_Temperature() time.sleep(2) except: State.ERROR_FLAG_3 = True return
def __init__(self, root): Frame.__init__(self, root) self.pfr = pifacerelayplus.PiFaceRelayPlus(pifacerelayplus.RELAY) self.pfr.init_board( { 'value': 0, 'direction': 0, 'pullup': 0 }, { 'value': 0, 'direction': 0, # Makes all pins outputs outputs 'pullup': 0 }) root.protocol( "WM_DELETE_WINDOW", self.on_closing ) # This will create a pop-up to confirm ending the program, and # if there is confirmation it will call the on_closing method # to tidy up before closing. # Bench control, Tab 1, variables self.lightOnImage = PhotoImage(file="icons/light-bulb.png") self.fanImage = PhotoImage(file="icons/ac.png") self.ironImage = PhotoImage(file="icons/iron-soldering.png") self.gpioONImage = PhotoImage(file="icons/switch.png") self.gpioOFFImage = PhotoImage(file="icons/switch-2.png") self.hairdryerImage = PhotoImage(file="icons/hairdryer.png") # Camera, Tab 2 variables self.camera = picamera.PiCamera() self.last_photo = None #declaring without defining. self.isVideoRecording = FALSE self.isTakingIntervalPhotos = FALSE self.intervalStillButtonPressed = FALSE self.intervalImageCounter = 0 self.photoInterval = 5 # interval in seconds. self.directory_interval = None self.file_name_interval = None self.intervalCamera = PhotoImage(file="icons/multiple-shots.png") self.videoCamera = PhotoImage(file="icons/video-camera.png") self.add = PhotoImage(file="icons/add.png") self.remove = PhotoImage(file="icons/minus.png") self.stillCamera = PhotoImage(file="icons/photo-camera.png") # Environment, Tab 3 variables self.pi = pigpio.pi() self.sensor = DHT22.sensor(self.pi, DHT_SENSOR_PIN) self.clock = PhotoImage(file="icons/clock.png") self.humidity = PhotoImage(file="icons/humidity.png") self.thermometer = PhotoImage(file="icons/thermometer.png") self.pack(fill=BOTH, expand=True) self.root = root self.root.title(PROGRAM_NAME) self.initUI()
def measure(led, lcd): try: (hum, tem) = DHT22.measure() if ((hum == 0) and (tem == 0)) or (hum > 100): raise ValueError('Invalid data received from sensor') lcd.write('\nHumidity: %s%%\n Temp: %sC\n\n' % (hum, tem)) led.off() except Exception as e: lcd.write(str(e) + '\n') led.on()
def main(): ##------------------------------------------------------------------------- ## Parse Command Line Arguments ##------------------------------------------------------------------------- ## create a parser object for understanding command-line arguments parser = argparse.ArgumentParser(description="Program description.") ## add flags parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Be verbose! (default = False)") ## add arguments parser.add_argument("--input", type=str, dest="input", help="The input.") args = parser.parse_args() ##------------------------------------------------------------------------- ## Create logger object ##------------------------------------------------------------------------- logger = logging.getLogger('MyLogger') logger.setLevel(logging.DEBUG) ## Set up console output LogConsoleHandler = logging.StreamHandler() if args.verbose: LogConsoleHandler.setLevel(logging.DEBUG) else: LogConsoleHandler.setLevel(logging.INFO) LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s') LogConsoleHandler.setFormatter(LogFormat) logger.addHandler(LogConsoleHandler) ## Set up file output # LogFileName = None # LogFileHandler = logging.FileHandler(LogFileName) # LogFileHandler.setLevel(logging.DEBUG) # LogFileHandler.setFormatter(LogFormat) # logger.addHandler(LogFileHandler) # os.system('modprobe w1-gpio') # os.system('modprobe w1-therm') ##------------------------------------------------------------------------- ## Read DS18B20 Temperature Sensors ##------------------------------------------------------------------------- temps = DS18B20.read() for temp in temps: logger.info('Temperature (DS18B20) = {:.1f} F'.format(temp)) ##------------------------------------------------------------------------- ## Read DHT22 Temperature and Humidity Sensor ##------------------------------------------------------------------------- temp_DHT, humidity = DHT22.read() logger.info('Temperature (DHT22) = {:.1f} F'.format(temp_DHT)) logger.info('Humidity (DHT22) = {:.0f} %'.format(humidity))
def main(): ##------------------------------------------------------------------------- ## Parse Command Line Arguments ##------------------------------------------------------------------------- ## create a parser object for understanding command-line arguments parser = argparse.ArgumentParser( description="Program description.") ## add flags parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Be verbose! (default = False)") ## add arguments parser.add_argument("--input", type=str, dest="input", help="The input.") args = parser.parse_args() ##------------------------------------------------------------------------- ## Create logger object ##------------------------------------------------------------------------- logger = logging.getLogger('MyLogger') logger.setLevel(logging.DEBUG) ## Set up console output LogConsoleHandler = logging.StreamHandler() if args.verbose: LogConsoleHandler.setLevel(logging.DEBUG) else: LogConsoleHandler.setLevel(logging.INFO) LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s') LogConsoleHandler.setFormatter(LogFormat) logger.addHandler(LogConsoleHandler) ## Set up file output # LogFileName = None # LogFileHandler = logging.FileHandler(LogFileName) # LogFileHandler.setLevel(logging.DEBUG) # LogFileHandler.setFormatter(LogFormat) # logger.addHandler(LogFileHandler) # os.system('modprobe w1-gpio') # os.system('modprobe w1-therm') ##------------------------------------------------------------------------- ## Read DS18B20 Temperature Sensors ##------------------------------------------------------------------------- temps = DS18B20.read() for temp in temps: logger.info('Temperature (DS18B20) = {:.1f} F'.format(temp)) ##------------------------------------------------------------------------- ## Read DHT22 Temperature and Humidity Sensor ##------------------------------------------------------------------------- temp_DHT, humidity = DHT22.read() logger.info('Temperature (DHT22) = {:.1f} F'.format(temp_DHT)) logger.info('Humidity (DHT22) = {:.0f} %'.format(humidity))
def getStats(self): pi = pigpio.pi() s = DHT22.sensor(pi, self.channel) s.trigger() sleep(.1) stats = {} stats['temperature'] = s.temperature() stats['humidity'] = s.humidity() s.cancel() pi.stop() return stats
def main(): sensor_handler = sensor.sensor() FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(filename=os.path.dirname(os.path.realpath(__file__)) + '/dht22.log', level=logging.DEBUG, format=FORMAT) logger = logging.getLogger('dht22') print "DHT22 Sensor:" readout = None counter = 0 try: pi = pigpio.pi() except ValueError: print "Failed to connect to PIGPIO (%s)" logger.error('Failed to connect to PIGPIO (%s)', ValueError) try: sensor_data = DHT22.sensor(pi, 17) except ValueError: print "Failed to connect to DHT22" logger.error('Failed to connect to DHT22 (%s)', ValueError) while (readout == None and counter < 5): counter += 1 # Get data from sensor sensor_data.trigger() time.sleep(0.2) humidity = sensor_data.humidity() temperature = sensor_data.temperature() if humidity != None and temperature != None and humidity >= 0 and humidity <= 100: readout = [humidity, temperature] saveSQLite(readout) sensor_handler.save_value(0, temperature) sensor_handler.save_value(1, humidity) print "Humidity: " + str(humidity) print "Temperature: " + str(temperature) counter = 10 else: time.sleep(5)
def main(): logging.basicConfig(format="%(asctime)-15s %(message)s", datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) parser = argparse.ArgumentParser(description='Climate') parser.add_argument('-i', '--interval', help='reporting interval in seconds') parser.add_argument('-d', '--display_only', help='only display, no reporting', action="store_true") args = parser.parse_args() if args.interval: Registry.reporting_interval = int(args.interval) display_only = args.display_only # REST client. aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Adafruit IO Feeds. temperature_feed = aio.feeds('10-cfr-climate-2nd-floor.temperature') humidity_feed = aio.feeds('10-cfr-climate-2nd-floor.humidity') while True: try: temperature, humidity = DHT22.get() temperature = f'{temperature:.1f}' humidity = f'{humidity:.1f}' if humidity is not None and temperature is not None: if not display_only: send_readings(aio, temperature, humidity, temperature_feed, humidity_feed) logging.info( f'Temp={temperature}*C Humidity={humidity}% Send={not display_only}' f' (next in {Registry.reporting_interval} secs)') else: logging.info( f'Failed to get readings, trying again in {Registry.reporting_interval} seconds' ) except Exception as ex: logging.exception('Cannot send data') # Avoid flooding Adafruit IO time.sleep(Registry.reporting_interval)
def main(): sensor_handler = sensor.sensor(); FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(filename=os.path.dirname(os.path.realpath(__file__)) + '/dht22.log', level=logging.DEBUG, format=FORMAT) logger = logging.getLogger('dht22') print "DHT22 Sensor:" readout = None counter = 0 try: pi = pigpio.pi() except ValueError: print "Failed to connect to PIGPIO (%s)" logger.error('Failed to connect to PIGPIO (%s)', ValueError); try: sensor_data = DHT22.sensor(pi, 17) except ValueError: print "Failed to connect to DHT22" logger.error('Failed to connect to DHT22 (%s)', ValueError); while (readout == None and counter < 5): counter += 1 # Get data from sensor sensor_data.trigger() time.sleep(0.2) humidity = sensor_data.humidity() temperature = sensor_data.temperature() if humidity != None and temperature != None and humidity >= 0 and humidity <= 100: readout = [humidity, temperature] saveSQLite(readout) sensor_handler.save_value(0, temperature) sensor_handler.save_value(1, humidity) print "Humidity: " + str(humidity) print "Temperature: " + str(temperature) counter = 10 else: time.sleep(5)
def temp(): #code for temp/humidity pi = pigpio.pi() s = DHT22.sensor(pi, 4) s.trigger() sleep(2) a = (s.humidity() / 1.) b = (s.temperature() / 1.) firstLabel = Label(leftFrame, text=a) firstLabel.grid(row=1, column=0, padx=10, pady=2) secondLabel = Label(leftFrame, text=b) secondLabel.grid(row=2, column=0, padx=10, pady=2) s.cancel() pi.stop()
def __init__(self): self.pi = pigpio.pi() self.sampledata = DHT22.sensor(self.pi, 4) print('start the sensor') print('trigger') #time.sleep(2) self.sampledata.trigger() time.sleep(2) print('trigger') self.sampledata.trigger() self.current = time.time() self.tempdata = '{:3.2f}'.format(self.sampledata.temperature() / 1.) self.humidata = '{:3.2f}'.format(self.sampledata.humidity() /1.)
class DHT22_Temp(Sensor): NAME = "Aussen-Temp" UNIT = "°C" REFRESH_TIME = 20 gpio = 6 dht22 = DHT22.sensor(pi, gpio) @classmethod def ReadSensorData(cls): cls.dht22.trigger() time.sleep(0.2) return float("{0:0.1f}".format(cls.dht22.temperature()))
def __init__(self, root): Frame.__init__(self, root) self.pfr = pifacerelayplus.PiFaceRelayPlus(pifacerelayplus.RELAY) self.pfr.init_board( { 'value': 0, 'direction': 0, 'pullup': 0}, { 'value': 0, 'direction': 0, # Makes all pins outputs outputs 'pullup': 0}) root.protocol("WM_DELETE_WINDOW", self.on_closing) # This will create a pop-up to confirm ending the program, and # if there is confirmation it will call the on_closing method # to tidy up before closing. # Bench control, Tab 1, variables self.lightOnImage = PhotoImage(file="icons/light-bulb.png") self.fanImage = PhotoImage(file="icons/ac.png") self.ironImage = PhotoImage(file="icons/iron-soldering.png") self.gpioONImage = PhotoImage(file="icons/switch.png") self.gpioOFFImage = PhotoImage(file="icons/switch-2.png") self.hairdryerImage = PhotoImage(file="icons/hairdryer.png") # Camera, Tab 2 variables self.camera = picamera.PiCamera() self.last_photo = None #declaring without defining. self.isVideoRecording = FALSE self.isTakingIntervalPhotos = FALSE self.intervalStillButtonPressed = FALSE self.intervalImageCounter = 0 self.photoInterval = 5 # interval in seconds. self.directory_interval = None self.file_name_interval = None self.intervalCamera = PhotoImage(file="icons/multiple-shots.png") self.videoCamera = PhotoImage(file="icons/video-camera.png") self.add = PhotoImage(file="icons/add.png") self.remove = PhotoImage(file="icons/minus.png") self.stillCamera = PhotoImage(file="icons/photo-camera.png") # Environment, Tab 3 variables self.pi = pigpio.pi() self.sensor = DHT22.sensor(self.pi, DHT_SENSOR_PIN) self.clock = PhotoImage(file="icons/clock.png") self.humidity = PhotoImage(file="icons/humidity.png") self.thermometer = PhotoImage(file="icons/thermometer.png") self.pack(fill=BOTH,expand=True) self.root = root self.root.title(PROGRAM_NAME) self.initUI()
def get_env_info(): import DHT22 import pigpio from time import sleep pi = pigpio.pi() s = DHT22.sensor(pi, 3) s.trigger() sleep(.01) ctemp = s.temperature() print('Humidity Percentage: {:3.2f}'.format(s.humidity() / 1.)) print('Celcius Temp: {:3.2f}'.format(ctemp / 1.)) print('F Temp: {:3.2f}'.format(ctemp * 9 / 5 + 32 / 1.)) s.cancel() pi.stop()
def main(): currTemperature = 0 currHumidity = 0 pi = pigpio.pi() s = DHT22.sensor(pi, 4) while True: s.trigger() time.sleep(0.2) if s.temperature() != currTemperature: pubMsg("babykeeper/temperature", s.temperature()) currTemperature = s.temperature() if s.humidity() != currHumidity: pubMsg("babykeeper/humidity", s.humidity()) currHumidity = s.humidity() time.sleep(1) # Overall INTERVAL second polling. s.cancel() pi.stop()
def Measure(self): __temperatures = [] __humidities = [] for sensor in self.__sensors: __container = DHT22.sensor(pi, sensor) __container.trigger() sleep(.1) if __container.temperature() is not None and __container.humidity( ) is not None: if __container.temperature() < 0 or __container.humidity() < 0: __temperatures.append(0) __humidities.append(0) else: __temperatures.append(__container.temperature()) __humidities.append(__container.humidity()) return __temperatures, __humidities
def Main(): currTemperature=0 currHumidity=0 #os.system("sudo pigpio") #subprocess.call(['sudo','pigpiod'],shell=True) # Intervals of about 2 seconds or less will eventually hang the DHT22. #INTERVAL=3 pi = pigpio.pi() s = DHT22.sensor(pi, 4) pubIp() curr=getAddress() while True: s.trigger() time.sleep(0.2) ''' print("{} {} {}".format( r, s.humidity(), s.temperature())) ''' if curr != getAddress(): pub() curr=getAddress() pubChangedTemperature() pubChangedHumidity() time.sleep(1) # Overall INTERVAL second polling. s.cancel() pi.stop()
def get_cur_temp_and_hum(sensor): # this connects to the pigpio daemon which must be started first retval = {'temperature': -999, 'humidity': -999} pi = pigpio.pi() # Pigpio DHT22 module should be in same folder as your program s = DHT22.sensor(pi, sensor) i = 0 while ((i < 6) and (int(retval['temperature']) <= -999)): i += 1 s.trigger() sleep(.05) # Necessary on faster Raspberry Pi's retval['humidity'] = round(s.humidity(), 1) retval['temperature'] = round(s.temperature(), 1) '''print("{} {} {:3.2f} {} {} {} {}".format( s.humidity(), s.temperature(), s.staleness(), s.bad_checksum(), s.short_message(), s.missing_message(), s.sensor_resets()))''' s.cancel() pi.stop() return retval
def temphum(user, datapin): try: last_measure = Humidity_temp.query.order_by( Humidity_temp.timestamp.desc()).first() except: last_measure = None if last_measure == None or datetime.utcnow().timestamp( ) - last_measure.timestamp >= user.humidity_temp_i * 60: pi = pigpio.pi() s = DHT22.sensor(pi, datapin) s.trigger() sleep(2) h = s.humidity() t = s.temperature() s.cancel() sleep(0.2) pi.stop() measure = Humidity_temp(humidity=h, temp=t, timestamp=datetime.utcnow().timestamp()) db.session.add(measure) db.session.commit()
def read_Current_Tempature(): "Reads the current Tempature" global Current_Temp pi = pigpio.pi() sensor = DHT22.sensor(pi, 4, LED=16, power=8) myWrite = WriteTempData.WriteTemp() while True: sleep(0.2) sensor.trigger() faren = sensor.temperature() faren = CtoF.C_to_F(faren) Current_Temp = faren print("Current Temp:", faren) display_CT.set('{:.4}'.format(float(faren))) myHum = sensor.humidity() print("Humidity is:", myHum) display_Hum.set('{:.4}'.format(float(myHum))) myWrite.write(str(Current_Temp), str(myHum)) sleep(3) sensor.cancel() pi.stop()
def measureTempHum(self): import DHT22 import pigpio import os os.system('sudo pigpiod') pi = pigpio.pi() s = DHT22.sensor(pi, self.echoGPIO) s.trigger() time.sleep(0.03) hum = s.humidity()/1.0 temp = s.temperature() / 1.0 print 'humdity is {0}'.format(hum) print 'temperature is {0}'.format(temp) if hum > 30 or temp > 30: print 'turning on AC' self.unsetSignal() time.sleep(5) else: print 'turning off AC' self.setSignal() time.sleep(5) s.cancel() time.sleep(0.5) pi.stop()
ch0 = data[1] * 256 + data[0] ch1 = data1[1] * 256 + data1[0] """ DHT22 code """ import pigpio import DHT22 import time ##import datetime ##from time import sleep ##import RPi.GPIO as GPIO ## must run sudo pigpiod from cmd prompt prior to running this script after ## every restart of PI. pi = pigpio.pi() ## Initiate GPIO for pigpio. dht22 = DHT22.sensor(pi, 17) ## use the actual GPIO pin name/number dht22.trigger() ## forces a reading. first reading is just junk. sleepTime = 3 ## must sleep at least 3 second to stop sensor hangs. def readDHT22(): dht22.trigger() humidity = " %.2f" % (dht22.humidity()) temp = " %.2f" % (dht22.temperature()) return (humidity, temp) def Temp_Tol(): temperature = int(temperature) if temperature + "%" > int(27.00): print("\n\n Temperature too High") else: print(" ")
OAUTH_TOKEN_SECRET='YtDYC2ztRVwCmVJ1mUT5liBjE6dHibnE8CWwlI9kjH9US' twitter = Twython(APP_KEY,APP_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET) #DB Connection dbserver = "localhost" dbuser = "******" dbpw = "22murraysbrae!" dbname = "weather" dbtable = "data" conn = MySQLdb.connect(host = dbserver,user = dbuser,passwd = dbpw,db = dbname) x = conn.cursor() #Setup Temp & Humidity Sensor (DHT22) pi = pigpio.pi() dht22 = DHT22.sensor(pi,12) #sensor on GPIO pin 12 dht22.trigger() sleepTime = 3 #Define Function to trigger DHT22 def ReadDHT22(): print ("Reading DHT22") #Get new Reading dht22.trigger() #Save values dht_humidity = '%.2f' % (dht22.humidity()) dht_temperature = '%.2f' % (dht22.temperature()) return (dht_humidity,dht_temperature) #Setup Temp & Pressure sensor (BMP085) bmp_sensor = BMP085.BMP085()
astro_logger.exception(ex) # Log exception info and continue… return csv_fields = ["meas_time", "temp", "hum", "watertemp", "CO2", "light"] measurement_interval = 60 while True: t_start = datetime.datetime.now() params = {} # for all sensors try to read them, if not make sure the script # does not block and fill None in file params["meas_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") try: h, t = DHT22.readSensor() #t, p, h = bme280.readBME280All() #use this for bme280 and outcomment line above params["hum"] = h params["temp"] = t except Exception as ex: astro_logger.exception(ex) # Log exception info and continue… pass try: wt = waterTemp.read_temp() params["watertemp"] = wt except Exception as ex: astro_logger.exception(ex) # Log exception info and continue… pass try:
def read_sensor(): temp, humidity = DHT22.read_sensor(SENSOR_PIN, 'F') return "%s,device=%s fahrenheit=%.1f,humidity=%.1f" % ( measurement, client_id, temp, humidity)
logFileName = ("/home/pi/lake_status/GetConditions.log") logging.basicConfig(filename=logFileName, level=loglevel, format='%(asctime)s %(levelname)s %(message)s') logging.debug("logger started") start_time = time.time() parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id$') parser.add_option ('-p', '--pythonanywhere', action='store_true', help='sends data to pythonanywhere database') parser.add_option ('-c', '--carriots', action='store_true', help='sends data to carriots') (options, args) = parser.parse_args() #get the data from the sensor (pigpiod must be running with root permission) logging.debug('trying to get data from dht22') try: pi = pigpio.pi() dht22 = DHT22.sensor(pi, 4, None, 24) #trigger the event, gather the data dht22.trigger() #check to see if data is relevant, first reading is generally bad, -999 is not right... count = 0 while dht22.temperature() > 150 or dht22.temperature() < -20: count = count + 1 #wait 3 seconds and try again. logging.debug('bad data from sensor, count : %10o' % count) time.sleep(3) dht22.trigger() #error occurred, twenty queries to sensor (1min) and no data. if count > 20: logging.error("Sensor didn't return any data. Exiting.") sys.exit(2)
import time import Adafruit_ADS1x15 import Adafruit_DHT import sys import paho.mqtt.client as paho import board import neopixel import DHT22 import pigpio import os #imports OS library for Shutdown control # Temperature & humidity Sensors pi = pigpio.pi() sensorIndoor = DHT22.sensor(pi, 23) sensorOutdoor = DHT22.sensor(pi, 24) # Relais GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # GPIO Nummern statt Board Nummern RELAIS_MAIN_GPIO = 12 RELAIS_1_GPIO = 7 GPIO.setup(RELAIS_MAIN_GPIO, GPIO.OUT) GPIO.setup(RELAIS_1_GPIO, GPIO.OUT) status_fridge = "off" status_mains = "off" # Counters messageCounter = 0 lowVoltageCounter = 0
self.cb = None if __name__ == "__main__": import time import pigpio import DHT22 # Intervals of about 2 seconds or less will eventually hang the DHT22. INTERVAL=3 pi = pigpio.pi() s = DHT22.sensor(pi, 4, LED=16, power=8) r = 0 next_reading = time.time() while True: r += 1 s.trigger() time.sleep(0.2) print("{} {} {} {:3.2f} {} {} {} {}".format( r, s.humidity(), s.temperature(), s.staleness(),
import DHT22 import pyb def measure(led, lcd): try: (hum, tem) = DHT22.measure() if ((hum == 0) and (tem == 0)) or (hum > 100): raise ValueError('Invalid data received from sensor') lcd.write('\nHumidity: %s%%\n Temp: %sC\n\n' % (hum, tem)) led.off() except Exception as e: lcd.write(str(e) + '\n') led.on() DHT22.init() lcd = pyb.LCD('X') lcd.light(True) led_red = pyb.LED(1) # 1 = Red while True: measure(led_red, lcd) pyb.delay(3000)
def readDHT22(): DHT22.triger() temperature = '%.2f' % (DHT22.temperature()) return temperature
def getHumidity: HT22.triger() humidity = '%.2f' % (DHT22.hymidity()) return humidity
from time import sleep try: if(not os.path.isfile('/var/run/pigpio.pid')): os.system("sudo pigpiod") print("PIGPIO: the deamon is launched") sleep(3) else: print("PIGPIO: the deamon was already launched") except Exception: pass # Initiate GPIO for pigpio pi = pigpio.pi() # Setup the sensor dht22 = DHT22.sensor(pi, 4) # use the actual GPIO pin name dht22.trigger() # We want our sleep time to be above 2 seconds. sleepTime = 3 def get_dht22_values(): # Wait few seconds before getting values sleep(sleepTime) # Get a new reading dht22.trigger() # Save our values humidity = '%.2f' % (dht22.humidity()) temp = '%.2f' % (dht22.temperature())
import pigpio import DHT22 from datetime import date import json from time import sleep import time pi = pigpio.pi() sleeptime = 3 maxtries = 3 #Set up sensor dht22 = DHT22.sensor(pi, 27) fileName = 'history.json' def readDHT(): #Get new reading dht22.trigger() #Return results as tuple return (dht22.humidity(), dht22.temperature()) #Get a good reading, the first one can be a write off (typically -999) def getReading(): counter = 0 #We cant go forever, so we give it maxtries tries before printing error humidity, temperature = readDHT() while(temperature < - 30 or temperature > 50):
s = air_quality.sensor(pi, 7) # set the GPIO pin number time.sleep(30) # Use 30s for a properly calibrated reading. g, r, c = s.read() # get the gpio, ratio and concentration in particles / 0.01 ft3 concentration_ugm3 = s.pcs_to_ugm3(c) # convert to SI units aqi = s.ugm3_to_aqi(concentration_ugm3) # convert SI units to US AQI (instantaneous only) return aqi if __name__ == "__main__": ''' Main program - reads all sensors and sends readings to thingspeak ''' pi = pigpio.pi() # Humidity and temp from DHT22 (outisde) s = DHT22.sensor(pi, PIN_DHT22, LED=None, power=8) s.trigger() time.sleep(0.2) humidity = s.humidity() temp1 = s.temperature() # Humidity and temp from DHT22 (inside) #si = DHT22.sensor(pi, PIN_DHT22i, LED=None, power=8) #si.trigger() #time.sleep(0.2) #humidityi = si.humidity() # temp and pressure from BMP085 temp2 = BMP085sensor.read_temperature() pressure = BMP085sensor.read_pressure()
observation = owm.weather_at_place('Ghaziabad,India') w = observation.get_weather() h = w.get_humidity() t = w.get_temperature('celsius') data = {} data['et'] = t['temp'] data['eh'] = h data['etmin'] = t['temp_min'] data['etmax'] = t['temp_max'] ### get weather data from sensor ### pi = pigpio.pi() s = DHT22.sensor(pi, 4, 27) s.trigger() time.sleep(0.2) data['it'] = s.temperature() data['ih'] = s.humidity() s.cancel() pi.stop() ### index data ### data['dt'] = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime()) json_data = json.dumps(data) print("{}".format(json_data))
#--------------------------------------------------------------------------- # SET UP SENSOR VARIABLES #--------------------------------------------------------------------------- sensor_value = {x: 'U' for x in s.SENSOR_SET} sensor_settings = collections.namedtuple('sensor_settings', 'enable ref unit min max type') sensor = {k: sensor_settings(*s.SENSOR_SET[k]) for k in s.SENSOR_SET} #------------------------------------------------------------------- # Get inside temperature and humidity #------------------------------------------------------------------- if sensor['inside_temp'].enable or sensor['inside_hum'].enable: try: DHT22_sensor = DHT22.sensor(pi, sensor['inside_temp'].ref) DHT22_sensor.trigger() time.sleep(0.2) #Do not over poll DHT22 DHT22_sensor.cancel() if sensor['inside_temp'].enable: sensor_value['inside_temp'] = DHT22_sensor.temperature() if sensor['inside_hum'].enable: sensor_value['inside_hum'] = DHT22_sensor.humidity() logger.info('Reading value from DHT22 sensor... OK') except ValueError: logger.warning('Failed to read DHT22 ({value_error})'.format( value_error=ValueError))
argNames = ['filename', 'temperature'] args = dict(zip(argNames, sys.argv)) # setting some default values, Pin # using BGM sensorPin = 19 sensorVoltagePin = 26 targetOutputPin = 12 # this is the pin giving signal to relay -> fan motor sleepTime = 3 targetTemperature = int(args['temperature']) # getting the input from argv pi = pigpio.pi() # turn on the sensor pi.set_mode(sensorVoltagePin, pigpio.OUTPUT) pi.write(sensorVoltagePin, True) # setup the DHT22 sensor pin dht22 = DHT22.sensor(pi, sensorPin) # setup the relay -> fan motor output pin pi.set_mode(targetOutputPin, pigpio.OUTPUT) # defined how to read the DHT22 def readDHT22(): dht22.trigger() humidity = '%.2f' % (dht22.humidity()) temp = '%.2f' % (dht22.temperature()) return (float(humidity), float(temp)) # the core program run try: print("[Please use Ctrl + C to termate the program]\n") print("Program Start...") print("When the temperature is HIGHER then " + str(targetTemperature) + ". The relay -> fan motor will turn on!\n")
CONTINUOUS_HIGH_RES_MODE_2 = 0x11 ONE_TIME_HIGH_RES_MODE_1 = 0x20 ONE_TIME_HIGH_RES_MODE_2 = 0x21 ONE_TIME_LOW_RES_MODE = 0x23 bus = smbus.SMBus(1) relay_pin1 = 23 relay_pin2 = 24 relay_pin3 = 25 temp_pin = 22 motion_pin = 18 # Initiate GPIO for pigpio pi = pigpio.pi() # Setup the sensor dht22 = DHT22.sensor(pi,temp_pin) # use the actual GPIO pin name dht22.trigger() # We want our sleep time to be above 3 seconds. sleepTime = 3 GPIO.setmode(GPIO.BCM) GPIO.setup(relay_pin1,GPIO.OUT) GPIO.setup(relay_pin2,GPIO.OUT) GPIO.setup(relay_pin3,GPIO.OUT) GPIO.setup(motion_pin, GPIO.IN) presence = GPIO.input(motion_pin) def readDHT22(): # Get a new reading
if __name__ == "__main__": import time import pigpio import DHT22 # Intervals of about 2 seconds or less will eventually hang the DHT22. INTERVAL = 5 pi = pigpio.pi() s = DHT22.sensor(pi, 4, LED=16, power=8) r = 0 next_reading = time.time() while True: r += 1 s.trigger() time.sleep(0.2) print("{} {} {} {:3.2f} {} {} {} {}".format( r, s.humidity(),
# main.py -- put your code here! import pyb import DHT22 # Turn blue LED on blueled=pyb.LED(4) blueled.on() DHT22.init() (hum, tem) = DHT22.measure() while True: print("humidite : " + str(hum) + " temperature : " + (str(tem))) pyb.delay(3000)
if __name__ == "__main__": import time import pigpio import DHT22 # Intervals of about 2 seconds or less will eventually hang the DHT22. INTERVAL=3 pi = pigpio.pi() # s = DHT22.sensor(pi, 22, LED=16, power=8) s = DHT22.sensor(pi, 17) r = 0 next_reading = time.time() while True: r += 1 s.trigger() time.sleep(0.2) print("{} humidity: {} temp(C): {} temp(F): {} {:3.2f} {} {} {} {}".format( r, s.humidity(), s.temperature(), s.temperature()*9/5+32, s.staleness(),
def __init__(self, root): Frame.__init__(self, root) # The following works with the Piface Relay+ ''' self.pfr = pifacerelayplus.PiFaceRelayPlus(pifacerelayplus.RELAY) self.pfr.init_board( { 'value': 0, 'direction': 0, 'pullup': 0}, { 'value': 0, 'direction': 0, # Makes all pins outputs outputs 'pullup': 0}) ''' root.protocol("WM_DELETE_WINDOW", self.on_closing) # This will create a pop-up to confirm ending the program, and # if there is confirmation it will call the on_closing method # to tidy up before closing. # Bench control, Tab 1, variables self.lightOnImage = PhotoImage(file="icons/light-bulb.png") self.fanImage = PhotoImage(file="icons/ac.png") self.ironImage = PhotoImage(file="icons/iron-soldering.png") self.gpioONImage = PhotoImage(file="icons/switch.png") self.gpioOFFImage = PhotoImage(file="icons/switch-2.png") self.hairdryerImage = PhotoImage(file="icons/hairdryer.png") # Camera, Tab 2 variables # Don't enable the camera if an actual camera is not connected to the RPi self.camera = picamera.PiCamera() self.last_photo = None #declaring without defining. self.isVideoRecording = FALSE self.isTakingIntervalPhotos = FALSE self.intervalStillButtonPressed = FALSE self.intervalImageCounter = 0 self.photoInterval = 5 # interval in seconds. self.directory_interval = None self.file_name_interval = None self.intervalCamera = PhotoImage(file="icons/multiple-shots.png") self.videoCamera = PhotoImage(file="icons/video-camera.png") self.add = PhotoImage(file="icons/add.png") self.remove = PhotoImage(file="icons/minus.png") self.stillCamera = PhotoImage(file="icons/photo-camera.png") # Environment, Tab 3 variables self.pi = pigpio.pi() # Don't setup the DHT sensor unless a sensor is actually connected self.sensor = DHT22.sensor(self.pi, DHT_SENSOR_PIN) self.clock = PhotoImage(file="icons/clock.png") self.humidity = PhotoImage(file="icons/humidity.png") self.thermometer = PhotoImage(file="icons/thermometer.png") # Setup relay GPIOS self.fan_gpio = 22 # On the relay board self.lights_gpio = 6 # On the relay board self.solder_iron_gpio = 10 # External relay self.hot_air_gpio = 9 # External relay self.pi.set_mode(self.hot_air_gpio,pigpio.OUTPUT) # Make output self.pi.set_mode(self.solder_iron_gpio,pigpio.OUTPUT) # Make output self.pi.set_mode(self.fan_gpio,pigpio.OUTPUT) # Make output self.pi.set_mode(self.lights_gpio,pigpio.OUTPUT) # Make output self.pi.write(self.hot_air_gpio,0) # Set to LOW self.pi.write(self.solder_iron_gpio,0) # Set to LOW self.pi.write(self.fan_gpio,0) # Set to LOW self.pi.write(self.lights_gpio,0) # Set to LOW self.pack(fill=BOTH,expand=True) self.root = root self.root.title(PROGRAM_NAME) self.initUI()
tls_version=ssl.PROTOCOL_TLSv1_2) mqtt_client.connect('Pittsburgh.local', port=8883, keepalive=60) mqtt_client.loop_start() import time import pigpio import DHT22 # Intervals of about 2 seconds or less will eventually hang the DHT22. INTERVAL = 3 pi = pigpio.pi() s = DHT22.sensor(pi, 17) r = 0 next_reading = time.time() while True: r += 1 s.trigger() time.sleep(0.2) payload = "{} {} {} {:3.2f} {} {} {} {}".format( r, s.humidity(), s.temperature(), s.staleness(), s.bad_checksum(),
# usr/bin python3 import pigpio import time pi = pigpio.pi() import DHT22 ## s = DHT22.sensor(pi, 17) #works with out led blinking s = DHT22.sensor(pi, 17, 27) # works and blinks led s.trigger() fo = open("/home/pi/temp_log.txt", "w") count = 0 while (count < 30000): time.sleep(60) s.trigger() localtime = time.asctime( time.localtime(time.time()) ) #print("Time : {0}".format(localtime)) fo.writelines("Time : {0}".format(localtime)); fo.writelines(' Humidity : {0:3.2f}'.format(s.humidity() / 1.)); #print('Humidity : {:3.2f}'.format(s.humidity() / 1.)) #print('Temp : {:3.2f}'.format((s.temperature() * 1.8) +32)) fo.writelines(' Temp : {0:3.2f}\n'.format((s.temperature() * 1.8) +32)); count = count + 1 fo.close() s.cancel() pi.stop()
import sys # Specify the path where you downloaded the pigpio DHT22.py module sys.path.append('/home/pi/progs') import pigpio # this connects to the pigpio daemon which must be started first pi = pigpio.pi() import DHT22 s = DHT22.sensor(pi, 4) s.trigger() print('{:3.2f}'.format(s.humidity() / 1.)) print('{:3.2f}'.format(s.temperature() / 1.)) s.cancel() pi.stop()
def __init__(self, pi, gpio, LED=None, power=None): """ Instantiate with the Pi and gpio to which the DHT22 output pin is connected. Optionally a LED may be specified. This will be blinked for each successful reading. Optionally a gpio used to power the sensor may be specified. This gpio will be set high to power the sensor. If the sensor locks it will be power cycled to restart the readings. Taking readings more often than about once every two seconds will eventually cause the DHT22 to hang. A 3 second interval seems OK. """ self.pi = pi self.gpio = gpio self.LED = LED self.power = power if power is not None: pi.write(power, 1) # Switch sensor on. time.sleep(2) self.powered = True self.cb = None atexit.register(self.cancel) self.bad_CS = 0 # Bad checksum count. self.bad_SM = 0 # Short message count. self.bad_MM = 0 # Missing message count. self.bad_SR = 0 # Sensor reset count. # Power cycle if timeout > MAX_TIMEOUTS. self.no_response = 0 self.MAX_NO_RESPONSE = 2 self.rhum = -999 self.temp = -999 self.tov = None self.high_tick = 0 self.bit = 40 print(("test")) pi.set_pull_up_down(gpio, pigpio.PUD_OFF) pi.set_watchdog(gpio, 0) # Kill any watchdogs. self.cb = pi.callback(gpio, pigpio.EITHER_EDGE, self._cb) def _cb(self, gpio, level, tick): """ Accumulate the 40 data bits. Format into 5 bytes, humidity high, humidity low, temperature high, temperature low, checksum. """ diff = pigpio.tickDiff(self.high_tick, tick) if level == 0: # Edge length determines if bit is 1 or 0. if diff >= 50: val = 1 if diff >= 200: # Bad bit? self.CS = 256 # Force bad checksum. else: val = 0 if self.bit >= 40: # Message complete. self.bit = 40 elif self.bit >= 32: # In checksum byte. self.CS = (self.CS << 1) + val if self.bit == 39: # 40th bit received. self.pi.set_watchdog(self.gpio, 0) self.no_response = 0 total = self.hH + self.hL + self.tH + self.tL if (total & 255) == self.CS: # Is checksum ok? self.rhum = ((self.hH << 8) + self.hL) * 0.1 if self.tH & 128: # Negative temperature. mult = -0.1 self.tH = self.tH & 127 else: mult = 0.1 self.temp = ((self.tH << 8) + self.tL) * mult self.tov = time.time() if self.LED is not None: self.pi.write(self.LED, 0) else: self.bad_CS += 1 elif self.bit >= 24: # in temp low byte self.tL = (self.tL << 1) + val elif self.bit >= 16: # in temp high byte self.tH = (self.tH << 1) + val elif self.bit >= 8: # in humidity low byte self.hL = (self.hL << 1) + val elif self.bit >= 0: # in humidity high byte self.hH = (self.hH << 1) + val else: # header bits pass self.bit += 1 elif level == 1: self.high_tick = tick if diff > 250000: self.bit = -2 self.hH = 0 self.hL = 0 self.tH = 0 self.tL = 0 self.CS = 0 else: # level == pigpio.TIMEOUT: self.pi.set_watchdog(self.gpio, 0) if self.bit < 8: # Too few data bits received. self.bad_MM += 1 # Bump missing message count. self.no_response += 1 if self.no_response > self.MAX_NO_RESPONSE: self.no_response = 0 self.bad_SR += 1 # Bump sensor reset count. if self.power is not None: self.powered = False self.pi.write(self.power, 0) time.sleep(2) self.pi.write(self.power, 1) time.sleep(2) self.powered = True elif self.bit < 39: # Short message receieved. self.bad_SM += 1 # Bump short message count. self.no_response = 0 else: # Full message received. self.no_response = 0 print(("test2")) def temperature(self): """Return current temperature.""" return self.temp def humidity(self): """Return current relative humidity.""" return self.rhum def staleness(self): """Return time since measurement made.""" if self.tov is not None: return time.time() - self.tov else: return - 999 def bad_checksum(self): """Return count of messages received with bad checksums.""" return self.bad_CS def short_message(self): """Return count of short messages.""" return self.bad_SM def missing_message(self): """Return count of missing messages.""" return self.bad_MM def sensor_resets(self): """Return count of power cycles because of sensor hangs.""" return self.bad_SR def trigger(self): """Trigger a new relative humidity and temperature reading.""" if self.powered: if self.LED is not None: self.pi.write(self.LED, 1) self.pi.write(self.gpio, pigpio.LOW) time.sleep(0.017) # 17 ms self.pi.set_mode(self.gpio, pigpio.INPUT) self.pi.set_watchdog(self.gpio, 200) def cancel(self): """Cancel the DHT22 sensor.""" self.pi.set_watchdog(self.gpio, 0) if self.cb is not None: self.cb.cancel() self.cb = None if __name__ == "__main__": print(("test3")) import time import pigpio import DHT22 ## Intervals of about 2 seconds or less will eventually hang the DHT22. INTERVAL = 3 pi = pigpio.pi() s = DHT22.sensor(pi, 17, LED=27, power=8) r = 0 ##print((r)) next_reading = time.time() while True: r += 1 s.trigger() time.sleep(0.2) print(("{} {} {} {:3.2f} {} {} {} {}".format( r, s.humidity(), s.temperature(), s.staleness(), s.bad_checksum(), s.short_message(), s.missing_message(), s.sensor_resets()))) next_reading += INTERVAL time.sleep(next_reading - time.time()) # Overall INTERVAL second polling. s.cancel() pi.stop()
def __init__(self, *a, **kw): DeviceType.__init__(self, *a, **kw) import DHT22 self.sens = DHT22.sensor(self.pi, self.pinNumber) self.recentLowTemp = (0, None) # time, temp self.recentPeriodSec = 30
self.cb = None if __name__ == "__main__": import time import pigpio import DHT22 # Intervals of about 2 seconds or less will eventually hang the DHT22. INTERVAL=3 pi = pigpio.pi() s = DHT22.sensor(pi, 22) r = 0 next_reading = time.time() while True: r += 1 s.trigger() time.sleep(0.2) print("{} {} {} {:3.2f} {} {} {} {}".format( r, s.humidity(), s.temperature(), s.staleness(),
import pigpio import DHT22 from time import sleep pi = pigpio.pi() dht22 = DHT22.sensor(pi, 4) dht22.trigger() sleepTime = 3 def readDHT22(): dht22.trigger() humidity = '%.2f' % (dht22.humidity()) temp = '%.2f' % (dht22.temperature()) return (humidity, temp) while True: humidity, temperature = readDHT22() print("Humidity is :" + humidity + "%") print("Temperature is :" + temperature + "C") sleep(sleepTime)
#!/usr/local/bin/python import RPi.GPIO as GPIO import urllib2 import urllib import time import pigpio import DHT22 pi = pigpio.pi() #dth22 sensor definition dht22 = DHT22.sensor(pi, 16) dht22.trigger() GPIO.setmode(GPIO.BOARD) #define the pin that goes to the circuit pin_to_circuit = 7 def rc_time (pin_to_circuit): count = 0 #Output on the pin for GPIO.setup(pin_to_circuit, GPIO.OUT) GPIO.output(pin_to_circuit, GPIO.LOW) time.sleep(0.1) #Change the pin back to input GPIO.setup(pin_to_circuit, GPIO.IN)