Add error handling

This commit is contained in:
sago35
2024-07-14 13:37:13 +09:00
parent 315dbef694
commit 19c9fe6db3
+11 -2
View File
@@ -5,11 +5,16 @@
package dht20 package dht20
import ( import (
"errors"
"time" "time"
"tinygo.org/x/drivers" "tinygo.org/x/drivers"
) )
var (
errUpdateCalledTooSoon = errors.New("Update() called within 80ms is invalid")
)
// Device wraps an I2C connection to a DHT20 device. // Device wraps an I2C connection to a DHT20 device.
type Device struct { type Device struct {
bus drivers.I2C bus drivers.I2C
@@ -63,9 +68,14 @@ func (d *Device) initRegisters() {
} }
// Update reads data from the sensor and updates the temperature and humidity values. // Update reads data from the sensor and updates the temperature and humidity values.
// Note that the values obtained by this function are from the previous call to Update.
// If you want to use the most recent values, shorten the interval at which Update is called.
func (d *Device) Update(which drivers.Measurement) error { func (d *Device) Update(which drivers.Measurement) error {
// Check if 80ms have passed since the last access // Check if 80ms have passed since the last access
if d.prevAccessTime.Add(80 * time.Millisecond).Before(time.Now()) { if time.Since(d.prevAccessTime) < 80*time.Millisecond {
return errUpdateCalledTooSoon
}
// Check the status word Bit[7] // Check the status word Bit[7]
d.data[0] = 0x71 d.data[0] = 0x71
d.bus.Tx(d.Address, d.data[:1], d.data[:1]) d.bus.Tx(d.Address, d.data[:1], d.data[:1])
@@ -88,7 +98,6 @@ func (d *Device) Update(which drivers.Measurement) error {
// Update the previous access time to the current time // Update the previous access time to the current time
d.prevAccessTime = time.Now() d.prevAccessTime = time.Now()
} }
}
return nil return nil
} }