From 5d320c70dbe7098f48d64d43a1ef333b738e1e79 Mon Sep 17 00:00:00 2001 From: Louis <15342503+SoulKa@users.noreply.github.com> Date: Tue, 16 Jan 2024 21:13:16 +0100 Subject: [PATCH] Add AHT20 example code (#71) * add AHT20 example code * add Precision() test --- aht20/aht20_test.go | 14 ++++++++++++++ aht20/example_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 aht20/example_test.go diff --git a/aht20/aht20_test.go b/aht20/aht20_test.go index 3ef3a79..ae1ddfc 100644 --- a/aht20/aht20_test.go +++ b/aht20/aht20_test.go @@ -174,3 +174,17 @@ func TestDev_SoftReset(t *testing.T) { t.Fatal(err) } } + +func TestDev_Precision(t *testing.T) { + dev := Dev{d: &i2c.Dev{Bus: &i2ctest.Playback{}, Addr: deviceAddress}, opts: DefaultOpts} + var env physic.Env + dev.Precision(&env) + + if env.Temperature == 0 { + t.Fatal("expected temperature precision") + } else if env.Pressure != 0 { + t.Fatal("expected no pressure precision") + } else if env.Humidity == 0 { + t.Fatal("expected humidity precision") + } +} diff --git a/aht20/example_test.go b/aht20/example_test.go new file mode 100644 index 0000000..6ef9baf --- /dev/null +++ b/aht20/example_test.go @@ -0,0 +1,41 @@ +// Copyright 2024 The Periph Authors. All rights reserved. +// Use of this source code is governed under the Apache License, Version 2.0 +// that can be found in the LICENSE file. + +package aht20_test + +import ( + "fmt" + "log" + "periph.io/x/conn/v3/i2c/i2creg" + "periph.io/x/conn/v3/physic" + "periph.io/x/devices/v3/aht20" + "periph.io/x/host/v3" +) + +func Example() { + // Make sure periph is initialized. + if _, err := host.Init(); err != nil { + log.Fatal(err) + } + + // Use i2creg I²C bus registry to find the first available I²C bus. + b, err := i2creg.Open("") + if err != nil { + log.Fatalf("failed to open I²C: %v", err) + } + defer b.Close() + + // Create a new AHT20 device using I²C bus. + d, err := aht20.NewI2C(b, nil) // nil for default options or &aht20.DefaultOpts + if err != nil { + log.Fatalf("failed to initialize AHT20: %v", err) + } + + // Read temperature and humidity from the sensor + e := physic.Env{} + if err := d.Sense(&e); err != nil { + log.Fatal(err) + } + fmt.Printf("%8s %9s\n", e.Temperature, e.Humidity) +}