main.go (1508B)
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 main 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 main() { 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 // The SGP30 returns 400ppm, 0ppb for 15 seconds at startup 49 // This exits with a positive result if non-default values are read 50 // But it cannot detect an error from just the readings since 400,0 51 // may be normal for the environment. 52 for start := time.Now(); time.Since(start) < time.Second*30; { 53 time.Sleep(1 * time.Second) 54 if co2, tvoc, err := d.ReadAirQuality(); err != nil { 55 log.Fatal(err) 56 } else { 57 fmt.Printf("CO2 : %d ppm\nTVOC: %d ppb\n", co2, tvoc) 58 59 if co2 > 400 && tvoc > 0 { 60 fmt.Printf("SGP30: Good readings detected\n") 61 break 62 } 63 } 64 } 65 }