1
0
mirror of https://github.com/kidoman/embd synced 2024-12-22 21:00:05 +01:00
embd/sensor/watersensor/watersensor.go

72 lines
1.3 KiB
Go
Raw Normal View History

2013-12-23 16:48:00 +05:30
// Package watersensor allows interfacing with the water sensor
2013-12-23 16:39:02 +05:30
package watersensor
import (
"log"
"sync"
"github.com/stianeikeland/go-rpio"
)
type watersensor struct {
waterPinNumber int
2013-12-23 16:48:00 +05:30
waterPin rpio.Pin
initialized bool
mu *sync.RWMutex
debug bool
2013-12-23 16:39:02 +05:30
}
2013-12-23 16:48:00 +05:30
// WaterSensor implements access to a water sensor
2013-12-23 16:39:02 +05:30
type WaterSensor interface {
2013-12-23 16:48:00 +05:30
// IsWet determines if there is water present on the sensor
2013-12-23 16:39:02 +05:30
IsWet() (b bool,err error)
}
2013-12-23 16:48:00 +05:30
// New creates a new WaterSensor interface
2013-12-23 16:39:02 +05:30
func New(pinNumber int) WaterSensor {
return &watersensor{waterPinNumber: pinNumber, mu: new(sync.RWMutex)}
}
func (d *watersensor) Setup() (err error) {
d.mu.RLock()
2013-12-23 16:48:00 +05:30
if d.initialized {
d.mu.RUnlock()
return
}
2013-12-23 16:39:02 +05:30
d.mu.RUnlock()
2013-12-23 16:48:00 +05:30
d.mu.Lock()
defer d.mu.Unlock()
2013-12-23 16:39:02 +05:30
2013-12-23 16:48:00 +05:30
if err = rpio.Open(); err != nil {
return
}
2013-12-23 16:39:02 +05:30
2013-12-23 16:48:00 +05:30
d.waterPin = rpio.Pin(d.waterPinNumber)
d.waterPin.Input()
d.initialized = true
2013-12-23 16:39:02 +05:30
2013-12-23 16:48:00 +05:30
return nil
2013-12-23 16:39:02 +05:30
}
2013-12-23 16:48:00 +05:30
// IsWet determines if there is water present on the sensor
2013-12-23 16:39:02 +05:30
func (d *watersensor) IsWet() (b bool, err error) {
if err = d.Setup(); err != nil {
return
}
if d.debug {
log.Print("Getting reading")
}
2013-12-23 16:48:00 +05:30
// Read the pin value of the sensor
2013-12-23 16:39:02 +05:30
if d.waterPin.Read() == rpio.High {
b=true
} else {
b=false
}
return
}