This commit is contained in:
bineagu 2017-05-19 16:10:25 +00:00 committed by GitHub
commit 1078122bac
1 changed files with 16 additions and 0 deletions

View File

@ -16,6 +16,8 @@ import (
"github.com/kidoman/embd"
)
const timeoutInterval = 10000000
type digitalPin struct {
id string
n int
@ -169,6 +171,8 @@ func (p *digitalPin) TimePulse(state int) (time.Duration, error) {
aroundState = embd.High
}
initTime := time.Now()
// Wait for any previous pulse to end
for {
v, err := p.read()
@ -179,6 +183,10 @@ func (p *digitalPin) TimePulse(state int) (time.Duration, error) {
if v == aroundState {
break
}
if time.Since(initTime).Nanoseconds() > timeoutInterval {
return 0, nil
}
}
// Wait until ECHO goes high
@ -191,6 +199,10 @@ func (p *digitalPin) TimePulse(state int) (time.Duration, error) {
if v == state {
break
}
if time.Since(initTime).Nanoseconds() > timeoutInterval {
return 0, nil
}
}
startTime := time.Now() // Record time when ECHO goes high
@ -205,6 +217,10 @@ func (p *digitalPin) TimePulse(state int) (time.Duration, error) {
if v == aroundState {
break
}
if time.Since(initTime).Nanoseconds() > timeoutInterval {
return 0, nil
}
}
return time.Since(startTime), nil // Calculate time lapsed for ECHO to transition from high to low