-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
raspi_hcsr04.go
93 lines (78 loc) · 2.02 KB
/
raspi_hcsr04.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//go:build example
// +build example
//
// Do not build by default.
package main
import (
"fmt"
"log"
"os"
"time"
"gobot.io/x/gobot/v2"
"gobot.io/x/gobot/v2/drivers/gpio"
"gobot.io/x/gobot/v2/platforms/raspi"
)
func main() {
const (
triggerOutput = "11"
echoInput = "13"
)
// this is mandatory for systems with defunct edge detection, although the "cdev" is used with an newer Kernel
// keep in mind, that this cause more inaccurate measurements
const pollEdgeDetection = true
opts := []interface{}{}
if pollEdgeDetection {
opts = append(opts, gpio.WithHCSR04UseEdgePolling())
}
a := raspi.NewAdaptor()
hcsr04 := gpio.NewHCSR04Driver(a, triggerOutput, echoInput, opts...)
work := func() {
if pollEdgeDetection {
fmt.Println("Please note that measurements are CPU consuming and will be more inaccurate with this setting.")
fmt.Println("After startup the system is under load and the measurement is very inaccurate, so wait a bit...")
time.Sleep(2000 * time.Millisecond)
}
if err := hcsr04.StartDistanceMonitor(); err != nil {
log.Fatal(err)
}
// first single shot
if v, err := hcsr04.MeasureDistance(); err != nil {
log.Fatal(err)
} else {
fmt.Printf("first single shot done: %5.3f m\n", v)
}
ticker := gobot.Every(1*time.Second, func() {
fmt.Printf("continuous measurement: %5.3f m\n", hcsr04.Distance())
})
gobot.After(5*time.Second, func() {
if err := hcsr04.StopDistanceMonitor(); err != nil {
log.Fatal(err)
}
ticker.Stop()
})
gobot.After(7*time.Second, func() {
// second single shot
if v, err := hcsr04.MeasureDistance(); err != nil {
log.Fatal(err)
} else {
fmt.Printf("second single shot done: %5.3f m\n", v)
}
// cleanup
if err := hcsr04.Halt(); err != nil {
log.Println(err)
}
if err := a.Finalize(); err != nil {
log.Println(err)
}
os.Exit(0)
})
}
robot := gobot.NewRobot("distanceBot",
[]gobot.Connection{a},
[]gobot.Device{hcsr04},
work,
)
if err := robot.Start(); err != nil {
panic(err)
}
}