-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
64 lines (47 loc) · 1.09 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
57
58
59
60
61
62
63
64
package main
import (
"fmt"
"golang.org/x/exp/io/i2c"
"time"
)
const (
TEMP_NO_HOLD = byte(0xF3)
HUMIDITY = byte(0xF5)
)
func check(err error) {
if err != nil {
panic(err)
}
}
func waitForRead() {
time.Sleep(500 * time.Millisecond)
}
func getTemp(d i2c.Device) (float64, float64) {
err := d.Write([]byte{TEMP_NO_HOLD})
check(err)
waitForRead()
response := make([]byte, 2)
check(d.Read(response))
temp := (int64(response[0])*256 + int64(response[1])) & 0xFFFC
tempC := -46.85 + (175.72 * float64(temp) / 65536.0)
tempF := tempC*1.8 + 32
// fmt.Printf("%.2fºF\n", tempF)
return tempF, tempC
}
func getRelativeHumidity(d i2c.Device) int64 {
err := d.Write([]byte{HUMIDITY})
check(err)
waitForRead()
response := make([]byte, 2)
check(d.Read(response))
data := (int64(response[0])*256 + int64(response[1])) & 0xFFFC
humidity := ((125 * data) / 65536) - 6
return humidity
}
func main() {
d, err := i2c.Open(&i2c.Devfs{Dev: "/dev/i2c-1"}, 0x40)
check(err)
tempF, _ := getTemp(*d)
humidity := getRelativeHumidity(*d)
fmt.Printf("temp=%.2f humidity=%d\n", tempF, humidity)
}