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