-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
56 lines (44 loc) · 1.03 KB
/
main.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
package main
import (
"fmt"
"time"
"periph.io/x/conn/v3/gpio"
"periph.io/x/conn/v3/gpio/gpioreg"
"periph.io/x/host/v3"
)
func main() {
// Initialize periph.io
if _, err := host.Init(); err != nil {
fmt.Println("Failed to initialize periph:", err)
return
}
// Define GPIO pins
trig := gpioreg.ByName("GPIO23")
echo := gpioreg.ByName("GPIO24")
if trig == nil || echo == nil {
fmt.Println("Failed to find GPIO pins")
return
}
fmt.Println("Distance Measurement In Progress")
// Set up pins
trig.Out(gpio.Low)
time.Sleep(2 * time.Second)
// Send trigger pulse
trig.Out(gpio.High)
time.Sleep(10 * time.Microsecond)
trig.Out(gpio.Low)
// Wait for echo to start
start := time.Now()
for echo.Read() == gpio.Low {
start = time.Now()
}
// Wait for echo to end
end := time.Now()
for echo.Read() == gpio.High {
end = time.Now()
}
// Calculate duration and distance
duration := end.Sub(start).Seconds()
distance := duration * 17150 // Speed of sound in air (343m/s)
fmt.Printf("Distance: %.2f cm\n", distance)
}