air-sensors

Air Quality Sensor library
git clone https://www.brianlane.com/git/air-sensors
Log | Files | Refs | README | LICENSE

example_test.go (1126B)


      1 // Copyright 2020 by Brian C. Lane <bcl@brianlane.com>. All rights reserved.
      2 // Use of this source code is governed under the Apache License, Version 2.0
      3 // that can be found in the LICENSE file.
      4 
      5 package sgp30_test
      6 
      7 import (
      8 	"fmt"
      9 	"log"
     10 	"time"
     11 
     12 	"periph.io/x/periph/conn/i2c/i2creg"
     13 	"periph.io/x/periph/host"
     14 
     15 	"github.com/bcl/air-sensors/sgp30"
     16 )
     17 
     18 func Example() {
     19 	// Make sure periph is initialized.
     20 	if _, err := host.Init(); err != nil {
     21 		log.Fatal(err)
     22 	}
     23 
     24 	// Open a handle to the first available I²C bus:
     25 	bus, err := i2creg.Open("")
     26 	if err != nil {
     27 		log.Fatal(err)
     28 	}
     29 	defer bus.Close()
     30 
     31 	d, err := sgp30.New(bus, ".sgp30_baseline", 30*time.Second)
     32 	if err != nil {
     33 		log.Fatal(err)
     34 	}
     35 	defer d.Halt() //nolint
     36 
     37 	sn, err := d.GetSerialNumber()
     38 	if err != nil {
     39 		log.Fatal(err)
     40 	}
     41 	fmt.Printf("Serial Number: %X\n", sn)
     42 
     43 	// Start measuring air quality
     44 	if err = d.StartMeasurements(); err != nil {
     45 		log.Fatal(err)
     46 	}
     47 
     48 	for {
     49 		time.Sleep(1 * time.Second)
     50 		if co2, tvoc, err := d.ReadAirQuality(); err != nil {
     51 			log.Fatal(err)
     52 		} else {
     53 			fmt.Printf("CO2 : %d ppm\nTVOC: %d ppb\n", co2, tvoc)
     54 		}
     55 	}
     56 }