ads1x15: fix a race condition

pull/1/head
Marc-Antoine Ruel 8 years ago
parent 41baeb565b
commit 641330bde8

@ -120,7 +120,7 @@ type Dev struct {
c i2c.Dev c i2c.Dev
name string name string
dataRates map[int]uint16 dataRates map[int]uint16
mu sync.Mutex mu sync.Mutex // For executePreparedQuery()
} }
// NewADS1015 creates a new driver for the ADS1015 (12-bit ADC). // NewADS1015 creates a new driver for the ADS1015 (12-bit ADC).
@ -387,14 +387,17 @@ var (
) )
type analogPin struct { type analogPin struct {
// Immutable.
adc *Dev adc *Dev
c Channel c Channel
query [3]byte query [3]byte
voltageMultiplier physic.ElectricPotential voltageMultiplier physic.ElectricPotential
waitTime time.Duration waitTime time.Duration
requestedFrequency physic.Frequency requestedFrequency physic.Frequency
stop chan struct{}
// Mutable.
mu sync.Mutex mu sync.Mutex
stop chan struct{}
} }
// Range returns the maximum supported range [min, max] of the values. // Range returns the maximum supported range [min, max] of the values.
@ -422,15 +425,14 @@ func (p *analogPin) ReadContinuous() <-chan analog.Reading {
} }
reading := make(chan analog.Reading, 16) reading := make(chan analog.Reading, 16)
p.stop = make(chan struct{}) p.stop = make(chan struct{})
go func() {
t := time.NewTicker(p.requestedFrequency.Duration()) t := time.NewTicker(p.requestedFrequency.Duration())
go func(s <-chan struct{}) {
defer t.Stop() defer t.Stop()
defer close(reading) defer close(reading)
for { for {
select { select {
case <-p.stop: case <-s:
return return
case <-t.C: case <-t.C:
value, err := p.Read() value, err := p.Read()
@ -441,7 +443,7 @@ func (p *analogPin) ReadContinuous() <-chan analog.Reading {
reading <- value reading <- value
} }
} }
}() }(p.stop)
return reading return reading
} }

Loading…
Cancel
Save