diff --git a/host/generic/digitalpin.go b/host/generic/digitalpin.go index 525eeb4..fb2fde6 100644 --- a/host/generic/digitalpin.go +++ b/host/generic/digitalpin.go @@ -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