-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Create hcsr04_driver.go #872
Closed
Closed
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5f21bb3
Create hcsr04_driver.go
Juan1ll0 02685ba
Fix PR sugestion
Juan1ll0 a09f56c
Update hcsr04_driver.go
Juan1ll0 9b9be1c
Update hcsr04_driver.go
Juan1ll0 ae72e3d
Merge branch 'dev' into Draft-PR-HCSR04
Juan1ll0 6c2f2cb
Start writing example code.
Juan1ll0 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,166 @@ | ||
package gpio | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"sync" | ||
"time" | ||
|
||
"gobot.io/x/gobot" | ||
"gobot.io/x/gobot/drivers/gpio" | ||
) | ||
|
||
const ( | ||
soundSpeed float32 = 343.0 // in [m/s] | ||
// the device can measure 2cm .. 4m, this means sweep distances between 4cm and 8m | ||
// this cause pulse durations between 0.12ms and 24ms (at 34.3 cm/ms, ~0.03 ms/cm, ~3ms/m) | ||
measurementCycle time.Duration = 60 // 60ms between two measurements | ||
MonitorUpdate time.Duration = 100 * time.Millisecond | ||
) | ||
|
||
// HCSR04 instance | ||
type HCSR04 struct { | ||
name string | ||
connection gobot.Adaptor | ||
triggerPin *gpio.DirectPinDriver | ||
echoPin *gpio.DirectPinDriver | ||
mux sync.Mutex | ||
Measure float32 // The last measure | ||
distanceMonitorControl chan int | ||
distanceMonitorStarted bool | ||
gobot.Commander | ||
} | ||
|
||
// NewHCSR04 creates a new HCSR04 instance | ||
func NewHCSR04(a gobot.Adaptor, triggerPinID string, echoPinID string) *HCSR04 { | ||
return &HCSR04{ | ||
name: gobot.DefaultName("HCSR04"), | ||
triggerPin: gpio.NewDirectPinDriver(a, triggerPinID), | ||
echoPin: gpio.NewDirectPinDriver(a, echoPinID), | ||
connection: a, | ||
Commander: gobot.NewCommander(), | ||
} | ||
} | ||
|
||
// MeasureDistance measure the distance in front of sensor in meters | ||
// and returns the measure | ||
// MeasureDistance triggers a distance measurement by the sensor | ||
// | ||
// ! MeasureDistance is not design to work in a fast loop | ||
// For this specific usage, use StartDistanceMonitor associated with GetDistance Instead | ||
func (hcsr04 *HCSR04) MeasureDistance() (float32, error) { | ||
hcsr04.mux.Lock() | ||
defer hcsr04.mux.Unlock() | ||
pulseDuration, err := hcsr04.measurePulse() | ||
if err != nil { | ||
return 0, err | ||
} | ||
hcsr04.Measure = pulseToDistance(pulseDuration) | ||
return hcsr04.Measure, nil | ||
} | ||
|
||
// GetDistance returns the last distance measured | ||
// Contrary to MeasureDistance, GetDistance does not trigger a distance measurement | ||
func (hcsr04 *HCSR04) GetDistance() float32 { | ||
return hcsr04.Measure | ||
} | ||
|
||
// StartDistanceMonitor starts a process which will keep Measure updated | ||
func (hcsr04 *HCSR04) StartDistanceMonitor() error { | ||
hcsr04.distanceMonitorControl = make(chan int) | ||
if hcsr04.distanceMonitorStarted { | ||
return errors.New("monitor already started") | ||
} | ||
go hcsr04.distanceMonitor() | ||
return nil | ||
} | ||
|
||
// StopDistanceMonitor stop the monitor process | ||
func (hcsr04 *HCSR04) StopDistanceMonitor() { | ||
if hcsr04.distanceMonitorStarted { | ||
hcsr04.distanceMonitorControl <- 1 | ||
} | ||
} | ||
|
||
func (h *HCSR04) Name() string { return h.name } | ||
|
||
func (h *HCSR04) SetName(n string) { h.name = n } | ||
|
||
func (h *HCSR04) Start() (err error) { return } | ||
|
||
func (h *HCSR04) Halt() (err error) { return } | ||
|
||
func (h *HCSR04) Connection() gobot.Connection { | ||
return h.connection.(gobot.Connection) | ||
} | ||
|
||
func (hcsr04 *HCSR04) distanceMonitor() { | ||
for { | ||
select { | ||
case <-hcsr04.distanceMonitorControl: | ||
hcsr04.distanceMonitorStarted = false | ||
return | ||
default: | ||
if _, err := hcsr04.MeasureDistance(); err != nil { | ||
fmt.Println("error: impossible to measure distance", err) | ||
} | ||
} | ||
time.Sleep(MonitorUpdate) | ||
} | ||
} | ||
|
||
func (hcsr04 *HCSR04) emitTrigger() { | ||
gen2thomas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
hcsr04.triggerPin.On() | ||
time.Sleep(10 * time.Microsecond) | ||
hcsr04.triggerPin.Off() | ||
} | ||
|
||
func (hcsr04 *HCSR04) measurePulse() (int64, error) { | ||
startChan := make(chan int64) | ||
stopChan := make(chan int64) | ||
startQuit := false | ||
stopQuit := false | ||
var startTime int64 | ||
var stopTime int64 | ||
go getPinStateChangeTime(hcsr04.echoPin, 1, startChan, &startQuit) | ||
hcsr04.emitTrigger() | ||
select { | ||
case t := <-startChan: | ||
startTime = t | ||
case <-time.After(measurementCycle * time.Millisecond): | ||
startQuit = true | ||
return 0, fmt.Errorf("echo not received after %d milliseconds", measurementCycle) | ||
} | ||
go getPinStateChangeTime(hcsr04.echoPin, 0, stopChan, &stopQuit) | ||
select { | ||
case t := <-stopChan: | ||
stopTime = t | ||
case <-time.After(measurementCycle * time.Millisecond): | ||
stopQuit = true | ||
return 0, fmt.Errorf("echo received for more than %d milliseconds", measurementCycle) | ||
} | ||
return stopTime - startTime, nil | ||
} | ||
|
||
func getPinStateChangeTime(pin *gpio.DirectPinDriver, state int, outChan chan int64, quit *bool) { | ||
|
||
for { | ||
readedValue, _ := pin.DigitalRead() | ||
// stop the loop if the state is different or a quit is done | ||
if readedValue == state || *quit { | ||
break | ||
} | ||
} | ||
time.Sleep(100) | ||
readedValue, err := pin.DigitalRead() | ||
if err != nil { | ||
fmt.Println(err) | ||
} | ||
if readedValue == state && !*quit { | ||
outChan <- time.Now().UnixNano() | ||
} | ||
} | ||
|
||
func pulseToDistance(pulseDuration int64) float32 { | ||
return float32(pulseDuration) / 1000000000.0 * soundSpeed / 2 | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because the file is already part of package "gpio", all this "gpio." needs to be removed. Otherwise an import cycle failure occurs.