Add analog sensor data event

This commit is contained in:
Adrian Zankich 2014-06-28 17:18:16 -07:00
parent 634756bbb0
commit 34ccc13ecb
2 changed files with 21 additions and 10 deletions

View File

@ -5,7 +5,6 @@ import (
"github.com/hybridgroup/gobot"
"github.com/hybridgroup/gobot/platforms/firmata"
"github.com/hybridgroup/gobot/platforms/gpio"
"time"
)
func main() {
@ -15,10 +14,9 @@ func main() {
led := gpio.NewLedDriver(firmataAdaptor, "led", "3")
work := func() {
gobot.Every(100*time.Millisecond, func() {
val := sensor.Read()
brightness := uint8(gobot.ToScale(gobot.FromScale(float64(val), 0, 1024), 0, 255))
fmt.Println("sensor", val)
gobot.On(sensor.Events["data"], func(data interface{}) {
brightness := uint8(gobot.ToScale(gobot.FromScale(float64(data.(int)), 0, 1024), 0, 255))
fmt.Println("sensor", data)
fmt.Println("brightness", brightness)
led.Brightness(brightness)
})

View File

@ -11,8 +11,11 @@ type AnalogSensorDriver struct {
func NewAnalogSensorDriver(a AnalogReader, name string, pin string) *AnalogSensorDriver {
d := &AnalogSensorDriver{
Driver: gobot.Driver{
Name: name,
Pin: pin,
Name: name,
Pin: pin,
Events: map[string]*gobot.Event{
"data": gobot.NewEvent(),
},
Commands: make(map[string]func(map[string]interface{}) interface{}),
Adaptor: a.(gobot.AdaptorInterface),
},
@ -27,9 +30,19 @@ func (a *AnalogSensorDriver) adaptor() AnalogReader {
return a.Driver.Adaptor.(AnalogReader)
}
func (a *AnalogSensorDriver) Start() bool { return true }
func (a *AnalogSensorDriver) Init() bool { return true }
func (a *AnalogSensorDriver) Halt() bool { return true }
func (a *AnalogSensorDriver) Start() bool {
value := 0
gobot.Every(a.Interval, func() {
newValue := a.Read()
if newValue != value && newValue != -1 {
value = newValue
gobot.Publish(a.Events["data"], value)
}
})
return true
}
func (a *AnalogSensorDriver) Init() bool { return true }
func (a *AnalogSensorDriver) Halt() bool { return true }
func (a *AnalogSensorDriver) Read() int {
return a.adaptor().AnalogRead(a.Pin)