def read_sensors():
    global session, date_time, lat, lon, temp, humid
    try:
        report = session.next()
        # Wait for a 'TPV' report and display the current time
        # To see all report data, uncomment the line below
        if report['class'] == 'TPV':
            if hasattr(report, 'time'):
                #print 'time\t\t', report.time
                date_time = report.time
            if hasattr(report, 'lat'):
                #print 'latitude\t', report.lat
                lat = report.lat
            if hasattr(report, 'lon'):
                #print 'longitude\t', report.lon
                lon = report.lon
            #print 'temperature\t', htu.read_temperature()
            #print 'humidity\t', htu.read_humidity()
            temp = htu.read_temperature()
            humid = htu.read_humidity()
            path_writer.writerow([date_time, lat, lon, temp, humid])
    
    except KeyError:
        pass
    except StopIteration:
        session = None
        print "GPSD has terminated"
Example #2
0
def read_sensors():
    global session, date_time, lat, lon, temp, humid
    try:
        report = session.next()
        # Wait for a 'TPV' report and display the current time
        # To see all report data, uncomment the line below
        if report['class'] == 'TPV':
            if hasattr(report, 'time'):
                #print 'time\t\t', report.time
                date_time = report.time
            if hasattr(report, 'lat'):
                #print 'latitude\t', report.lat
                lat = report.lat
            if hasattr(report, 'lon'):
                #print 'longitude\t', report.lon
                lon = report.lon
            #print 'temperature\t', htu.read_temperature()
            #print 'humidity\t', htu.read_humidity()
            temp = htu.read_temperature()
            humid = htu.read_humidity()
            path_writer.writerow([date_time, lat, lon, temp, humid])

    except KeyError:
        pass
    except StopIteration:
        session = None
        print "GPSD has terminated"
Example #3
0
def prog(filename="/home/pi/data/htu21df.log", sleeptime=3600):
	while True:
		# reset sensor and collect data for next log entry.
		HTU21DF.htu_reset
		temperature = HTU21DF.read_temperature()
		humidity = HTU21DF.read_humidity()
		cur_date = datetime.date.today()
		cur_time = time.time()
		data = [cur_date, cur_time, temperature, humidity]
	
		# save new data entry
		write_to_log(filename, data)
	
		# sleep until ready to collect next measurements.
		time.sleep(sleeptime)
Example #4
0
def prog(filename="/home/pi/data/htu21df.log", sleeptime=3600):
    while True:
        # reset sensor and collect data for next log entry.
        HTU21DF.htu_reset
        temperature = HTU21DF.read_temperature()
        humidity = HTU21DF.read_humidity()
        cur_date = datetime.date.today()
        cur_time = time.time()
        data = [cur_date, cur_time, temperature, humidity]

        # save new data entry
        write_to_log(filename, data)

        # sleep until ready to collect next measurements.
        time.sleep(sleeptime)
Example #5
0
def getTemperature():
  tempList = []
  for x in range(100):
     HTU21DF.htu_reset
     tempList.append(
       celcius_to_fahrenheit(HTU21DF.read_temperature())
     )
  return median(tempList)
Example #6
0
def prog(filename):
    # reset sensor and collect data.
    # reset sensor and collect data.  temp=tempsensor.readTempC()
    HTU21DF.htu_reset
    humidity = HTU21DF.read_humidity()
    temp1 = HTU21DF.read_temperature()
    barometer = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
    pressure = barometer.read_pressure()
    temp2 = barometer.read_temperature()
    temp = (temp1 + temp2) / 2
    lux = readLux()
    datetime = strftime("%Y-%m-%d\t%H:%M:%S")
    data = [datetime, temp, humidity, pressure, lux]
    # savenewdataentry
    write_to_log(filename, data)
    hour = strftime("%H")
    if float(hour) < 7:
        write_lux("/home/pi/lux.csv", lux)
def prog(filename):
    err = 0
    try:
        print("Reading humidity")
        HTU21DF.htu_reset
        humidity = HTU21DF.read_humidity()
        temp1 = HTU21DF.read_temperature()
        time.sleep(5)
    except:
        print("Failed")
        humidity = "NA"
        temp1 = 0
        err = 1
    try:
        print("Reading the barometer")
        barometer = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
        pressure = barometer.read_pressure()
        temp2 = barometer.read_temperature()
        time.sleep(5)
    except:
        print("Failed")
        pressure = "NA"
        temp2 = 0
        err = 1
    if (temp1 == 0 or temp2 == 0):
        temp = temp1 + temp2
    else:
        temp = (temp1 + temp2) / 2
    try:
        print("Reading Lux level")
        lux = readLux()
        time.sleep(5)
    except:
        print("Failed")
        lux = ""
        err = 1
    datetime = strftime("%Y-%m-%d\t%H:%M:%S")
    data = [datetime, temp, humidity, pressure, lux]
    # savenewdataentry
    write_to_log(filename, data)
    hour = strftime("%H")
    if int(hour) < 7:
        write_lux("/home/pi/lux.csv", lux)
    return err
Example #8
0
def prog(filename):
	err=0
	try:
		print ("Reading humidity")
		HTU21DF.htu_reset
		humidity=HTU21DF.read_humidity()
		temp1=HTU21DF.read_temperature()
		time.sleep(5)
	except:
		print ("Failed")
		humidity="NA"
		temp1=0
		err=1
	try:
		print ("Reading the barometer")
		barometer = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
		pressure=barometer.read_pressure()
		temp2=barometer.read_temperature()
		time.sleep(5)
	except:
		print ("Failed")
		pressure="NA"
		temp2=0
		err=1
	if (temp1==0 or temp2==0):
		temp=temp1+temp2
	else:
		temp=(temp1+temp2)/2
	try:
		print ("Reading Lux level")
		lux=readLux()
		time.sleep(5)
	except:
		print ("Failed")
		lux=""
		err=1
	datetime=strftime("%Y-%m-%d\t%H:%M:%S")
	data=[datetime,temp,humidity,pressure,lux]
	# savenewdataentry
	write_to_log(filename,data)
	hour=strftime("%H")
        if int(hour) < 7: 
            write_lux("/home/pi/lux.csv",lux) 
	return err
Example #9
0
def ReadSensors():
    global measuredTemp
    global measuredHumidity
    global reportCount
    global reportEvery

    measuredTemp = HTU21DF.read_temperature()
    measuredHumidity = HTU21DF.read_humidity()
    displayValues(
        str(round(measuredTemp, 1)) + " deg C",
        str(round(measuredHumidity, 1)) + " %")

    if (reportCount == reportEvery):
        # Send data to the web service
        reqString = 'http://api.marc-jennings.co.uk/InsecureUploadOfData.php?temperature=' + str(
            measuredTemp) + '&humidity=' + str(measuredHumidity)
        req = urllib2.Request(reqString)
        resp = urllib2.urlopen(req)

    reportCount = reportCount + 1
    if (reportCount > reportEvery):
        reportCount = 1
def prog(filename="/home/pi/behaviorRoomEnv.log", sleeptime=600):
    while True:
        # reset sensor and collect data for next log entry.
        temp = tempsensor.readTempC()
        humidity = HTU21DF.read_humidity()
        tempPres = MPL3115A2.pressure()
        lux = readLux()
        ## calculate average lux for 100 readings
        datetime = strftime("%Y-%m-%d\t%H:%M:%S")
        data = [datetime, temp, humidity, tempPres[1], lux]

        # save new data entry
        write_to_log(filename, data)

        # sleep until ready to collect next measurements.
        time.sleep(sleeptime)
Example #11
0
def sensorReadingProcess(logfileLock, filename, sleeptime):
    while True:
        # reset sensor and collect data for next log entry.
        # TODO: Make this section of code resistant to hardware failures by inserting "nil" values for missing data when appropriate
        temp = tempsensor.readTempC()
        humidity = HTU21DF.read_humidity()
        tempPres = MPL3115A2.pressure()
        lux = readLux()
        ## calculate average lux for 100 readings
        datetime = strftime("%Y-%m-%d\t%H:%M:%S")
        data = [datetime, temp, humidity, tempPres[1], lux]

        # save new data entry, blocking I/O operation
        logfileLock.acquire()
        write_to_log(filename, data)
        logfileLock.release()
        # sleep until ready to collect next measurements.
        time.sleep(sleeptime)
# A simple program to test the driver

import time
import HTU21DF

while True:
	print("sending reset...")
	HTU21DF.htu_reset
	temperature = HTU21DF.read_temperature()
	print("The temperature is %f C." % temperature)
	time.sleep(1)
	humidity = HTU21DF.read_humidity()
	print("The humidity is %F percent." % humidity)
	time.sleep(1)
Example #13
0
 def init(self):
     HTU21DF.htu_reset()
import time
import HTU21DF

while True:
    print("Sending reset....")
    HTU21DF.htu_reset
    temperature = HTU21DF.read_temperature()
    print("The temperatur is %f C" % temperature)
Example #15
0
 def read_values(self):
     logging.info('Performing measurement ...')
     self._temperature = HTU21DF.read_temperature()
     self._humidity = HTU21DF.read_humidity()
     logging.info('Got measurement: temperature: {}, humidity: {}'.format(
         self._temperature, self._temperature))
Example #16
0
# -*- coding: utf-8 -*-
###############################################################################
# test_htu21df.py                                                             #
# (c) https://github.com/thomaspfeiffer-git 2016                              #
###############################################################################
"""Tests sensor HTU21DF (humidity, temperature."""

import sys
from time import sleep, strftime

sys.path.append('../libs')
sys.path.append('../libs/sensors')

import HTU21DF  # temperature, humidity

htu21df = HTU21DF.HTU21DF()

while True:
    htu21df_temperature = htu21df.read_temperature()
    htu21df_humidity = htu21df.read_humidity()

    values = ":".join("{:.2f}".format(d) for d in [htu21df_humidity,    \
                                                   htu21df_temperature])
    print(strftime("%Y%m%d %X:"), values)
    # print("HTU21DF    | Humi  | {:>8.2f} | % rF    |".format(htu21df_humidity))
    # print("HTU21DF    | Temp  | {:>8.2f} | C       |".format(htu21df_temperature))

    sleep(1)

# eof #
Example #17
0
#!/usr/bin/python
import os
import sys
from datetime import datetime
import HTU21DF

home_dir = "/home/pi"
cam_name = "raspcam01"

if not os.path.isdir("%s/sensor" % home_dir):
    os.mkdir("%s/sensor" % home_dir)

dt_now = datetime.now()
dt_str1 = dt_now.strftime("%Y/%m/%d %H:%M:%S")
dt_str2 = dt_now.strftime("%Y%m%d")

fn = "%s/sensor/%s_sensor_%s.csv" % (home_dir, cam_name, dt_str2)

f = open(fn, "a")

HTU21DF.htu_reset()
temp = HTU21DF.read_temperature()
humid = HTU21DF.read_humidity()

f.write("%s,%s,%s\n" % (dt_str1, temp, humid))

f.close()
def getHumidity(temperature):
  tempList = []
  for x in range(50):
     HTU21DF.htu_reset
     tempList.append(HTU21DF.read_humidity(temperature))
  return median(tempList)
def getTemperature():
  HTU21DF.htu_reset()
  return HTU21DF.read_temperature()
Example #20
0
import time
import HTU21DF



def median(x):
  m,r= divmod(len(x),2)
  if r:
    return sorted(x)[m]
  return sum(sorted(x)[m-1:m+1])/2

def average(x):
  return sum(x)/len(x)


tempList = []
for x in range(1000):
   HTU21DF.htu_reset
   tempList.append(HTU21DF.read_temperature())


print 'median is {0}'.format(median(tempList))
print 'average is {0}'.format(average(tempList))
print 'minimum value is {0}, maximum value is {1}'.format(min(tempList), max(tempList))
print 'difference is {0}'.format(max(tempList) - min(tempList))
Example #21
0
def main():
    """main part"""

    qvalue_temp_indoor = SensorValue("ID_01", "TempWohnzimmerIndoor",
                                     SensorValue_Data.Types.Temp, "°C")
    qvalue_humi_indoor = SensorValue("ID_02", "HumiWohnzimmerIndoor",
                                     SensorValue_Data.Types.Humi, "% rF")
    qvalue_temp_outdoor = SensorValue("ID_03", "TempWohnzimmerOutdoor",
                                      SensorValue_Data.Types.Temp, "°C")
    qvalue_humi_outdoor = SensorValue("ID_04", "HumiWohnzimmerOutdoor",
                                      SensorValue_Data.Types.Humi, "% rF")
    qvalue_pressure = SensorValue("ID_05", "Luftdruck",
                                  SensorValue_Data.Types.Pressure, "hPa")
    qvalue_temp_realoutdoor = SensorValue("ID_12", "TempRealOutdoor",
                                          SensorValue_Data.Types.Temp, "°C")
    qvalue_temp_indoor2 = SensorValue("ID_13", "TempWohnzimmerFenster",
                                      SensorValue_Data.Types.Temp, "°C")

    sq.register(qvalue_temp_indoor)
    sq.register(qvalue_humi_indoor)
    sq.register(qvalue_temp_outdoor)
    sq.register(qvalue_humi_outdoor)
    sq.register(qvalue_pressure)
    sq.register(qvalue_temp_realoutdoor)
    sq.register(qvalue_temp_indoor2)

    bme280   = BME280.BME280(qvalue_pressure=qvalue_pressure, \
                             qvalue_temp=qvalue_temp_indoor,  \
                             qvalue_humi=qvalue_humi_indoor)
    global ds1820_1
    ds1820_1 = DS1820.DS1820("/sys/bus/w1/devices/28-000006d62eb1/w1_slave",
                             qvalue_temp_realoutdoor)
    ds1820_2 = DS1820.DS1820("/sys/bus/w1/devices/28-000006dc8d42/w1_slave",
                             qvalue_temp_indoor2)
    htu21df = HTU21DF.HTU21DF(qvalue_temp=qvalue_temp_outdoor,
                              qvalue_humi=qvalue_humi_outdoor)
    cpu = CPU.CPU()

    rrd_template    = DS_TEMPINDOOR      + ":" + \
                      DS_TEMPOUTDOOR     + ":" + \
                      DS_HUMIINDOOR      + ":" + \
                      DS_HUMIOUTDOOR     + ":" + \
                      DS_REALTEMPOUTDOOR + ":" + \
                      DS_TEMPINDOOR2     + ":" + \
                      DS_AIRPRESSURE     + ":" + \
                      DS_TEMPCPU

    while True:
        bme280_pressure = bme280.read_pressure() / 100.0  # indoor #
        bme280_temperature = bme280.read_temperature()
        bme280_humidity = bme280.read_humidity()
        if platform == Platform.NANOPI:
            ds1820_1.consume_cpu_start()
        ds1820_1_temperature = ds1820_1.read_temperature()
        ds1820_2_temperature = ds1820_2.read_temperature()
        if platform == Platform.NANOPI:
            ds1820_1.consume_cpu_stop()
        htu21df_temperature = htu21df.read_temperature()  # outdoor #
        htu21df_humidity = htu21df.read_humidity()
        cpu_temp = cpu.read_temperature()

        rrd_data = "N:" + \
                   ":".join("{:.2f}".format(d) for d in [bme280_temperature,   \
                                                         htu21df_temperature,  \
                                                         bme280_humidity,      \
                                                         htu21df_humidity,     \
                                                         ds1820_1_temperature, \
                                                         ds1820_2_temperature, \
                                                         bme280_pressure,   \
                                                         cpu_temp])

        # print(rrd_template)
        print(strftime("%Y%m%d %X:"), rrd_data)
        rrdtool.update(DATAFILE, "--template", rrd_template, rrd_data)

        sleep(45)
#let's pretend we are ready for Python 3
from __future__ import print_function

import HTU21DF
import math
import time

#For my Raspbery Pi B+ it is 1, read your docs
BUS_NO = 1

#For my device, the I2C address is 0x40
ADDR_HTU21 = 0x40

#Initialize with bus_no and ADDR
htu = HTU21DF.HTU21DF(BUS_NO, ADDR_HTU21)

#Performing a soft reset (should reset the values in User register)
htu.soft_reset()

#Let's print some info about the sensor.
#Loading into variable, so we do not have to use the I2C bus
user_reg = htu.read_user_reg()
htu.print_user_reg(user_reg)

#HTU21D-F reading temperature (a CRC check is performed, but on error, only message is printed!)
t_c = htu.read_temp_degC()  #in degree Celsius
#HTU21D-F reading humidity (a CRC is checked; on error, only message is printed!)
hum = htu.read_humidity_percent()  #in % (relative humidity)
print("Values reaad: Temp [degC]: {}, RH [%] {}".format(t_c, hum))