Exemplo n.º 1
0
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()
Exemplo n.º 2
0
    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())
Exemplo n.º 3
0
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}
Exemplo n.º 4
0
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 __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()
Exemplo n.º 6
0
 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
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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()
Exemplo n.º 10
0
 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.)
Exemplo n.º 11
0
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()
Exemplo n.º 13
0
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 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()
Exemplo n.º 16
0
    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
Exemplo n.º 17
0
    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()
Exemplo n.º 18
0
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()
Exemplo n.º 19
0
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
Exemplo n.º 20
0
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()
Exemplo n.º 21
0
 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()
Exemplo n.º 22
0
 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
Exemplo n.º 23
0
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()
Exemplo n.º 24
0
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")
Exemplo n.º 25
0
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
Exemplo n.º 26
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(),
Exemplo n.º 27
0
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())
    #controls
    #tempSetPoint = df_config['TempSetPoint'].values[0]
    #tempSetPointList = [26,28,30,32,34]
    i = 0
    #tempSetPoint = 30 #tempSetPointList[i]
    margin = 0

    freq = 10
    k = 1  #proportional control coefficient, if temp is one degree celcius below set point, turn on 100%
    #pi_fan = pigpio.pi()
    # pi_heater = pigpio.pi()
    rt = 24  #room temp
    k2 = 7.14

    pi = pigpio.pi()
    s = DHT22.sensor(pi, 24)
    r = 0
    next_reading = time.time()

    pi.set_mode(fan_pin, pigpio.OUTPUT)
    pi.set_mode(heater_pin, pigpio.OUTPUT)
    pi.set_PWM_frequency(heater_pin, freq)

    #initialize fan and heater off
    pi.write(fan_pin, 0)
    pi.write(heater_pin, 0)
    HeaterStatus = "OFF"
    FanStatus = "OFF"
    tempPrev = 25

    try:
Exemplo n.º 29
0
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
Exemplo n.º 30
0
    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)
Exemplo n.º 31
0
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

sleepTime = 900

baseDir = '/sys/bus/w1/devices/'
#deviceFolder = glob.glob(baseDir + '28-000006c8044b')[0]
deviceFolderOut = glob.glob(baseDir + '28-000006c8044b')[0]
deviceFolderIn2 = glob.glob(baseDir + '28-041591ae04ff')[0]
deviceFolderIn3 = glob.glob(baseDir + '28-01159110bcff')[0]
deviceFileOut = deviceFolderOut + '/w1_slave'
deviceFileIn2 = deviceFolderIn2 + '/w1_slave'
deviceFileIn3 = deviceFolderIn3 + '/w1_slave'

pi = pigpio.pi()
dht22 = DHT22.sensor(pi,4,17)
dht22.trigger()

json_key = json.load(open('/home/pi/zend_dht/credentials.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gspCred = False
worksheet = False

dbconn = sqlite3.connect('/home/pi/dht.db')
dbcurs = dbconn.cursor()
print("Meteo station v1.3")

def readTempRaw(deviceFile):
        f = open(deviceFile, 'r')
        lines = f.readlines()
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()
Exemplo n.º 33
0
	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()
Exemplo n.º 34
0
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(" ")
Exemplo n.º 35
0
    for i in current:
        # print (i["_id"], " out: ", i["outside"]["temp"], "  room:", i["room"]["temp"])
        if out_temp > i["outside"]["temp"]:
            lower_out += 1
        if room_temp > i["room"]["temp"]:
            lower_in += 1
    if lower_in >= 3 and lower_out >= 3:
        return "close"
    return "open"


pi = pigpio.pi()

degree = u"\u00b0"

s = DHT22.sensor(pi, 4)  # near
s2 = DHT22.sensor(pi, 17)  # outside
s3 = DHT22.sensor(pi, 18)  # living room

window_pin = 23
pi.set_mode(window_pin, pigpio.INPUT)
pi.set_pull_up_down(window_pin, pigpio.PUD_UP)

window_status = pi.read(window_pin)

room_temp = []
room_humidity = []
out_temp = []
out_humidity = []
living_room_temp = []
living_room_humidity = []
Exemplo n.º 36
0
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):
Exemplo n.º 37
0
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))
from time import sleep
import datetime

import urllib2, urllib, httplib
import pigpio
import DHT22
import os
GPIO.setmode(GPIO.BOARD)

#============================================================================
#Information about temperature, humidity, cpu, disk, RAM

# Initiate GPIO for pigpio
pi = pigpio.pi()
# Setup the sensor
dht22 = DHT22.sensor(pi, 21)  # gpio pin name for sensor
dht22.trigger()


def readDHT22():
    # Get a new reading
    dht22.trigger()
    # Save our values
    humidity = '%.2f' % (dht22.humidity())
    temp = '%.2f' % (dht22.temperature())

    return (humidity, temp)


# Return CPU temperature as a character string
def getCPUtemperature():
Exemplo n.º 39
0
 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
  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()
Exemplo n.º 41
0
# Setup RPi GPIO pins
PIN_DHT22 = 8
PIN_BMP085_SDA = 0
PIN_BMP085_SCL = 0
PIN_TGS2600 = 0

# Setup constants
slack = Slacker(SLACKAPI)

# main loop
if __name__ == "__main__":

    pi = pigpio.pi()

    # Humidity and temp from DHT22
    s = DHT22.sensor(pi, PIN_DHT22, LED=None, power=8)
    s.trigger()
    time.sleep(0.2)
    humidity = s.humidity()
    temp1 = s.temperature()

    # temp and pressure from BMP085
    temp2 = BMP085sensor.read_temperature()
    pressure = BMP085sensor.read_pressure()
    hpapressure = pressure / 100
    # calc average temp of 2 sensors
    temperature = 0
    temperature = (temp1 + temp2) / 2
    tempf = (temperature * 9 / 5) + 32
    # get reading from air quality sensor
    #airq =
Exemplo n.º 42
0
# 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()
Exemplo n.º 43
0

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(),
Exemplo n.º 44
0
#! /usr/bin/python
#
# mytemp.py
# Read and test the DHT22 sensor on the Pi remmeber you can read more than every 2 seconds form the sensor.
# D. Cappello Oct 2016
#
# NOTE don't forget to sudo pigpiod to get that going BEFORE you run this script 
import pigpio
import DHT22
import datetime as dt
from time import sleep, strftime, gmtime
#
# Initiate GPIO for pigpio
pi = pigpio.pi()
# Setup the Sensor
dht22 = DHT22.sensor(pi, 27) # use the actual GPIO pin name
# take a reading the first one doesn't count
dht22.trigger()

# We need to sleep for more than 2 seconds so we don't overwhelm the sensor
SleepTime=5

# define a function to get the readings
def ReadDHT22():
	# get a new reading
	dht22.trigger()
	# Save our values
	humidity = '%.2f' % (dht22.humidity())
	temp = '%.2f' % (dht22.temperature())
	ftemp = float(temp) * 1.8 + 32
	return (humidity,str(ftemp))
Exemplo n.º 45
0
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(),
Exemplo n.º 46
0
    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()
Exemplo n.º 47
0
        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(),
Exemplo n.º 48
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, 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(),
Exemplo n.º 49
0
    #---------------------------------------------------------------------------
    # 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))
Exemplo n.º 50
0
#!/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)
  
Exemplo n.º 51
0
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)
Exemplo n.º 52
0
tehu_pin = 4
fan_pin = 17
cool_pin = 27
heat_pin = 22

cool_off_minimum_wait_secs = 180

cool_on_humidity = 55
cool_off_humidity = cool_on_humidity - 1

# This will be set from the database which is checked every minute
extra_cool_10x = None

pi = pigpio.pi()
s = DHT22.sensor(pi, tehu_pin)

def update_cool(cool_on):
    i = int(not(cool_on))
    pi.write(fan_pin,  i)
    pi.write(cool_pin, i)
    return cool_on

def want_cool_on(te, hu):
    return hu > humidity_max

last_cool_off_time = time.time()
cool_on = update_cool(False)

while True:
    s.trigger()