From 97b1dae34753b900c65e8420c1e85098aaf47d74 Mon Sep 17 00:00:00 2001 From: Neagu Bogdan Date: Sat, 21 May 2016 20:01:27 +0300 Subject: [PATCH] Added timeout to TimePulse --- host/generic/digitalpin.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/host/generic/digitalpin.go b/host/generic/digitalpin.go index 80a81ea..2e00845 100644 --- a/host/generic/digitalpin.go +++ b/host/generic/digitalpin.go @@ -15,6 +15,8 @@ import ( "github.com/kidoman/embd" ) +const timeoutInterval = 10000000 + type digitalPin struct { id string n int @@ -165,6 +167,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() @@ -175,6 +179,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 @@ -187,6 +195,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 @@ -201,6 +213,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