Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make ultrasonic timeout configurable #1723

Merged
merged 1 commit into from
Jan 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions components/sensor/ultrasonic/ultrasonic.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type AttrConfig struct {
TriggerPin string `json:"trigger_pin"`
EchoInterrupt string `json:"echo_interrupt_pin"`
Board string `json:"board"`
TimeoutMs uint `json:"timeout_ms,omitempty"`
}

// Validate ensures all parts of the config are valid.
Expand Down Expand Up @@ -88,6 +89,13 @@ func newSensor(ctx context.Context, deps registry.Dependencies, name string, con
if err := s.triggerPin.Set(ctx, false, nil); err != nil {
return nil, errors.Wrap(err, "ultrasonic: cannot set trigger pin to low")
}

if config.TimeoutMs > 0 {
s.timeoutMs = config.TimeoutMs
} else {
// default to 1 sec
s.timeoutMs = 1000
}
s.intChan = make(chan bool)
s.echoInterrupt.AddCallback(s.intChan)
return s, nil
Expand All @@ -100,6 +108,7 @@ type Sensor struct {
echoInterrupt board.DigitalInterrupt
triggerPin board.GPIOPin
intChan chan bool
timeoutMs uint
generic.Unimplemented
}

Expand All @@ -119,15 +128,15 @@ func (s *Sensor) Readings(ctx context.Context, extra map[string]interface{}) (ma
timeB = time.Now()
case <-ctx.Done():
return nil, errors.New("ultrasonic: context canceled")
case <-time.After(time.Second * 1):
case <-time.After(time.Millisecond * time.Duration(s.timeoutMs)):
return nil, errors.New("ultrasonic timeout")
}
select {
case <-s.intChan:
timeA = time.Now()
case <-ctx.Done():
return nil, errors.New("ultrasonic: context canceled")
case <-time.After(time.Second * 1):
case <-time.After(time.Millisecond * time.Duration(s.timeoutMs)):
return nil, errors.New("ultrasonic timeout")
}
dist := timeA.Sub(timeB).Seconds() * 340 / 2
Expand Down