mirror of
https://github.com/tinygo-org/drivers.git
synced 2026-09-07 15:29:01 +00:00
Add error handling
This commit is contained in:
+11
-2
@@ -5,11 +5,16 @@
|
||||
package dht20
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"tinygo.org/x/drivers"
|
||||
)
|
||||
|
||||
var (
|
||||
errUpdateCalledTooSoon = errors.New("Update() called within 80ms is invalid")
|
||||
)
|
||||
|
||||
// Device wraps an I2C connection to a DHT20 device.
|
||||
type Device struct {
|
||||
bus drivers.I2C
|
||||
@@ -63,9 +68,14 @@ func (d *Device) initRegisters() {
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// 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]
|
||||
d.data[0] = 0x71
|
||||
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
|
||||
d.prevAccessTime = time.Now()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user