Added timeout to TimePulse

This commit is contained in:
Neagu Bogdan 2016-05-21 20:01:27 +03:00
parent bfcd1345fe
commit 97b1dae347
1 changed files with 16 additions and 0 deletions

View File

@ -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