Example #1
0
    def __init__(self,
                 ccs811_address=0x5b,
                 bme280_address=0x77,
                 tmp117_address=0x48,
                 ccs811_n_samples=1):
        self.lock = _thread.allocate_lock()
        self.ccs811_n_samples = ccs811_n_samples

        self.ccs811 = qwiic_ccs811.QwiicCcs811(address=ccs811_address)
        self.bme280 = qwiic_bme280.QwiicBme280(address=bme280_address)
        self.tmp117 = qwiic_tmp117.QwiicTmp117(address=tmp117_address)

        self.ccs811.begin()
        self.bme280.begin()
        self.tmp117.begin()

        # The conversion and averaging affect who long we will have to wait
        # for a conversion. See the TMP117 data sheet.
        self.tmp117.set_avg(qwiic_tmp117.QwiicTmp117.CONV_AVG_8)
        self.tmp117.set_cycle(qwiic_tmp117.QwiicTmp117.CONV_CYCLE_2)

        self.tvoc_q = []
        self.eco2_q = []
        self.pres_q = []
        self.tdry_q = []
        self.rh_q = []

        _thread.start_new_thread(self.read_loop, (None, ))
        # Sleep so that the measure thread can start
        time.sleep(1)
Example #2
0
    def __init__(self, title, co2_tvoc="co2"):
        self.title = title
        self.co2_tvoc = co2_tvoc
        logging.debug(self.title + ' init started')
        self.sensor = qwiic_ccs811.QwiicCcs811()

        self.sensor.begin()
Example #3
0
def runSensors():
    myBME280 = qwiic_bme280.QwiicBme280()
    myCCS811 = qwiic_ccs811.QwiicCcs811()

    if my BME280.is_connected() == False:
        print("The Qwiic BME280 device isn't connected to the system. Please check your connection", \
              file=sys.stderr)
        return
Example #4
0
 def initCCS811(self):
     try:
         self.ccs811 = qwiic_ccs811.QwiicCcs811(address=0x5a)
         if self.ccs811.is_connected() == False:
             raise "Sensor not connected"
         self.ccs811.begin()
     except Exception as e:
         print("error establishing ccs811",str(e))
Example #5
0
 def __init__(self):
     self.sensor = qwiic_ccs811.QwiicCcs811()
     if self.sensor.is_connected() == False:
         print(
             "CCS811 Sensor isn't connected to the system. Please check your connection",
             file=sys.stderr)
         sys.exit(0)
     else:
         print("CCS811 Sensor start")
         self.sensor.begin()
Example #6
0
def create_ccs811(verbose=False):
    """ Return a ccs811 object to access this sensor. Raises an error if it cannot connect. """
    new_ccs811 = qwiic_ccs811.QwiicCcs811()  #i2c_driver = i2c_bus)
    new_ccs811.begin()

    if not new_ccs811.connected:
        raise Exception(f"Cannot connect to ccs811 on i2c_bus {i2c_bus}")
    # Mode 1 = read every 1s, constant heat (more accurate?)
    # Mode 2 = every 10s, pulse heat
    # Mode 3 = every 60s, pulse heat
    #new_ccs811.set_drive_mode  (1)
    new_ccs811.set_drive_mode(2)
    return new_ccs811
Example #7
0
def runExample():

	print("\nSparkFun CCS811 Sensor Example 3 - NTC data to CCS811 for compensation. \n")
	mySensor = qwiic_ccs811.QwiicCcs811()

	if mySensor.connected == False:
		print("The Qwiic CCS811 device isn't connected to the system. Please check your connection", \
			file=sys.stderr)
		return

	mySensor.begin()

	mySensor.referance_resistance = 9950

	while True:

		if mySensor.data_available():

			mySensor.read_algorithm_results()

			print("CO2:\t%.3f ppm" % mySensor.CO2)

			print("tVOC:\t%.3f ppb" % mySensor.TVOC)

			mySensor.read_ntc()
			print("Measured Resistance: %.3f ohms" % mySensor.resistance)

			readTemperature = mySensor.temperature
			print("Converted Temperature: %.2f deg C" % readTemperature)

			mySensor.set_environmental_data( 50, readTemperature)

		elif mySensor.check_status_error():

			error = mySensor.get_error_register();
			if error == 0xFF:   
				# communication error
				print("Failed to get Error ID register from sensor")
			else:
				strErr = "Unknown Error"
				for code in _deviceErrors.keys():
					if error & code:
						strErr = _deviceErrors[code]
						break
				print("Device Error: %s" % strErr)

		time.sleep(1)
Example #8
0
def runExample():

    print(
        "\nSparkFun CCS811 Sensor Example 3 - NTC data to CCS811 for compensation. \n"
    )
    mySensor = qwiic_ccs811.QwiicCcs811()

    if mySensor.connected == False:
        print("The Qwiic CCS811 device isn't connected to the system. Please check your connection", \
         file=sys.stderr)
        return

    mySensor.begin()

    while True:

        humidityVariable = random.randrange(0, 10000) / 100  # 0 to 100%
        temperatureVariable = random.randrange(500, 7000) / 100  #5C to 70C

        print("New humidity and temperature:")
        print("  Humidity:    %.2f percent relative" % humidityVariable)
        print("  Temperature: %.2f degrees C" % temperatureVariable)

        mySensor.set_environmental_data(humidityVariable, temperatureVariable)
        if mySensor.data_available():

            mySensor.read_algorithm_results()

            print("  CO2:\t%.3f ppm" % mySensor.CO2)
            print("  tVOC:\t%.3f ppb\n" % mySensor.TVOC)

        elif mySensor.check_status_error():

            error = mySensor.get_error_register()
            if error == 0xFF:
                # communication error
                print("Failed to get Error ID register from sensor")
            else:
                strErr = "Unknown Error"
                for code in _deviceErrors.keys():
                    if error & code:
                        strErr = _deviceErrors[code]
                        break
                print("Device Error: %s" % strErr)

        time.sleep(1)
Example #9
0
def runExample():

	mySensor = qwiic_ccs811.QwiicCcs811()

	if mySensor.connected == False:
		print("The Qwiic CCS811 device isn't connected to the system. Please check your connection", \
			file=sys.stderr)
		return

	mySensor.begin()
	mySensor.read_algorithm_results()
	time.sleep(3)
	mySensor.read_algorithm_results()
	time.sleep(3)
	mySensor.read_algorithm_results()
	print(datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),end=",")
	print("%.3f" % mySensor.CO2,end = ",")
	print("%.3f" % mySensor.TVOC)	
Example #10
0
def runExample():

    print("\nSparkFun CCS811 Sensor Basic Example \n")
    mySensor = qwiic_ccs811.QwiicCcs811()

    if mySensor.connected == False:
        print("The Qwiic CCS811 device isn't connected to the system. Please check your connection", \
         file=sys.stderr)
        return

    mySensor.begin()

    while True:

        mySensor.read_algorithm_results()

        print("CO2:\t%.3f" % mySensor.CO2)

        print("tVOC:\t%.3f\n" % mySensor.TVOC)

        time.sleep(1)
Example #11
0
import os
import qwiic_ccs811
from time import sleep
from dbwriter import writeinflux

# Variables used and inputted into the fuctions
location = os.getenv("DEVICE_DB_LOCATION")
measurement_name = "ccs811"
# startup of sensor so it doesn't just write 0 values
# API Documentation @ https://qwiic-ccs811-py.readthedocs.io/en/latest/apiref.html

mySensor = qwiic_ccs811.QwiicCcs811()
mySensor.begin()
mySensor.read_algorithm_results()
sleep(30)


def convertdata():
    # take the readings and store it on the board so it can be pulled
    mySensor.read_algorithm_results()
    # format the data as a single measurement for influx
    co2_level = {
        "measurement": measurement_name,
        "tags": {
            "location": location
        },
        "fields": {
            "co2": float(mySensor.get_co2())
        }
    }
    tvoc_level = {
Example #12
0
print()

devices = qwiic.list_devices()

if len(devices) == 0:
	print("No Devices Found!")
	exit(1)

print("Found the following device(s):")
for device in devices:
	print(device[1])


myJoystick = qwiic_joystick.QwiicJoystick()
bme280 = qwiic_bme280.QwiicBme280()
ccs811 = qwiic_ccs811.QwiicCcs811()

if myJoystick.connected == True:
	useJoystick = True
	myJoystick.begin()

if bme280.connected == True:
	useBme280 = True
	bme280.begin()

	bme280.filter = 1  		# 0 to 4 is valid. Filter coefficient. See 3.4.4
	bme280.standby_time = 0 	# 0 to 7 valid. Time between readings. See table 27.
	
	bme280.over_sample = 1			# 0 to 16 are valid. 0 disables temp sensing. See table 24.
	bme280.pressure_oversample = 1	# 0 to 16 are valid. 0 disables pressure sensing. See table 23.
	bme280.humidity_oversample = 1	# 0 to 16 are valid. 0 disables humidity sensing. See table 19.
Example #13
0
def main():
    constants.hostname = socket.gethostname()
    if ((len(constants.hostname) < 1)
        or (constants.hostname == "undefined")):
        print("could not determine hostname")
        sys.exit()

    os.chdir("/home/pi/Projects/sensor-box")
    logger.logEvent("sensor-box.py started at " + str(datetime.datetime.now()))
    # using CCS811 mode 1 for internal measurement every second
    ccs811Sensor = qwiic_ccs811.QwiicCcs811()
    bme280Sensor = qwiic_bme280.QwiicBme280()
    if (HASPM25):
        pm25Sensor = smbus.SMBus(1)
    pm1count = -1
    pm10count = -1
    pm25count = -1
    if (ccs811Sensor.connected == False) or (bme280Sensor.connected == False):
        logger.logEvent("failed to connect to sensors")
        sys.exit(-1)

    ccs811Sensor.begin()
    bme280Sensor.begin()

    yesterday = 0
    today = 1
    baseValues = [ 0, 0, 0, 0, 0, 0]
    baseValueSet = False
    baseValue = 0
    baseIndex = 0

    config = constants.hostname + ".conf"
    if (exists(config)):
        with open(config) as c:
            baseValue = int(c.read())
            ccs811Sensor.set_baseline(baseValue)
            baseValueSet = True
            if (DEBUG):
                print("read baseline from " + config)

    while True:
        today = time.localtime().tm_mday
        if (yesterday != today):
            if (DEBUG):
                print("yesterday", yesterday, "not equal to today",today)
                logger.logEvent("yesterday "  + str(yesterday) + " not equal to today " + str(today))
            uptime = os.popen('uptime -s').read() [:-1]
            logger.logSensorHeader("#boot time " + uptime)
            logger.logSensorHeader("time,temp,humid,CO2,tVOC,PM1.0,PM2.5,PM10.0")
            logger.logEventHeader("#boot time " + uptime)
            logger.logEventHeader("#description of event")

            baseline = ccs811Sensor.get_baseline()
            logger.logEvent("#baseline at day rollover " + str(baseline))
            yesterday = today
            if (baseline != baseValue) and (baseValueSet == True):
                if (DEBUG):
                    logger.logEvent("#baseline " + str(baseline) + " does not match baseValue " + str(baseValue) + ", resetting")
                ccs811Sensor.set_baseline(baseValue)
                
            
        if (baseValueSet == False):
            interval = 10
            if ((time.localtime().tm_min % interval) == 0):
                baseline = ccs811Sensor.get_baseline()
                if (baseline >= constants.maxBaseline):
                    if (DEBUG):
                        logger.logEvent("baseline too high, using 0: " + str(baseline))
                    baseline = 0
                if (DEBUG):
                    logger.logEvent("#baseline " + str(interval) + " min read " + str(baseline))
                baseValues[baseIndex] = baseline
                baseIndex +=1
                logger.logEvent("#basevalues " + str(baseValues))
                if (baseIndex == 6):
                    baseIndex = 0
                if (checkBaseline(baseValues)):
                    logger.logEvent("#baseline set to " + str(baseline))
                    baseValue = baseline
                    ccs811Sensor.set_baseline(baseValue)
                    with open(config, 'w') as c:
                        c.write(str(baseValue))
                    baseValueSet = True
        else:
            interval = 10
            if ((time.localtime().tm_min % interval) == 0):
                baseline = ccs811Sensor.get_baseline()
                if (DEBUG):
                    logger.logEvent("#baseline " + str(interval) + " min read " + str(baseline))
                if (baseline != baseValue) and (baseValueSet == True):
                    if (DEBUG):
                        logger.logEvent("#baseline " + str(baseline) + " does not match baseValue " + str(baseValue) + ", resetting")
                    ccs811Sensor.set_baseline(baseValue)
        humidity = bme280Sensor.humidity
        
        if (HASPM25):
            pm25Data = pm25Sensor.read_i2c_block_data(0x12, 0x00, 32)
            pm1count = (pm25Data[4]<<8) + pm25Data[5]
            pm10count = (pm25Data[8]<<8) + pm25Data[9]
            pm25count = (pm25Data[6]<<8) + pm25Data[7]

        tempCelsius = bme280Sensor.temperature_celsius
        ccs811Sensor.set_environmental_data(humidity, tempCelsius)

        #TODO my stretto reads 4C lower than the reported temperature
        #tempCelsius -= 4

        if ccs811Sensor.data_available():
            ccs811Sensor.read_algorithm_results()
            if (ccs811Sensor.CO2 > 2**14):
                logString = '#error CO2 {:.2f}'.format(ccs811Sensor.CO2)
                logger.logEvent(logString)
            elif (ccs811Sensor.TVOC > 2**14):
                logString = '#error tVOC {:.2f}'.format(ccs811Sensor.TVOC)
                logger.logEvent(logString)
            else:
                logString = '{:.2f},{:.2f},{:d},{:d},{:d},{:d},{:d}'.format(
                    tempCelsius, humidity, 
                    ccs811Sensor.CO2,
                    ccs811Sensor.TVOC,
                    pm1count, pm25count, pm10count)
                logger.logSensor(logString)
                if DEBUG:
                    print(logString)
        time.sleep(60)