mirror of
https://github.com/kidoman/embd
synced 2024-06-06 11:07:48 +02:00
improved ultrasonic sensor
This commit is contained in:
parent
adc3d47305
commit
0e2e648a07
|
@ -2,6 +2,7 @@
|
||||||
package us020
|
package us020
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
@ -82,24 +83,37 @@ func (d *US020) Distance() (float64, error) {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
glog.V(2).Infof("us020: trigerring pulse")
|
// Ready the goroutine to measure return pulse.
|
||||||
|
done := make(chan time.Duration)
|
||||||
|
errChan := make(chan error)
|
||||||
|
go func() {
|
||||||
|
glog.V(2).Infof("us020: waiting for echo to go high")
|
||||||
|
duration, err := d.EchoPin.TimePulse(embd.High)
|
||||||
|
if err != nil {
|
||||||
|
errChan <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
done <- duration
|
||||||
|
}()
|
||||||
|
|
||||||
// Generate a TRIGGER pulse
|
// Generate a TRIGGER pulse.
|
||||||
|
glog.V(2).Infof("us020: trigerring pulse")
|
||||||
d.TriggerPin.Write(embd.High)
|
d.TriggerPin.Write(embd.High)
|
||||||
time.Sleep(pulseDelay)
|
time.Sleep(pulseDelay)
|
||||||
d.TriggerPin.Write(embd.Low)
|
d.TriggerPin.Write(embd.Low)
|
||||||
|
|
||||||
glog.V(2).Infof("us020: waiting for echo to go high")
|
// Wait for data on channel or timeout.
|
||||||
|
t := time.NewTimer(time.Millisecond * 200)
|
||||||
duration, err := d.EchoPin.TimePulse(embd.High)
|
select {
|
||||||
if err != nil {
|
case <-t.C:
|
||||||
return 0, err
|
return 0, errors.New("timeout on ultrasonic pulse")
|
||||||
|
case duration := <-done:
|
||||||
|
distance := float64(duration.Nanoseconds()) / 10000000 * (d.speedSound / 2)
|
||||||
|
return distance, nil
|
||||||
|
case e := <-errChan:
|
||||||
|
return 0, e
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate the distance based on the time computed
|
|
||||||
distance := float64(duration.Nanoseconds()) / 10000000 * (d.speedSound / 2)
|
|
||||||
|
|
||||||
return distance, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close.
|
// Close.
|
||||||
|
|
Loading…
Reference in New Issue
Block a user