|
SHT30传感器直接接在I2C的接口上,然后直接上代码就行了。不知道这缩进咋回事。- package main
- import (
- "bytes"
- "encoding/binary"
- "fmt"
- "os"
- "syscall"
- "time"
- )
- func getTempAndHum() (temp, hum string) {
- addr := 0x44
- f, err := os.OpenFile("/dev/i2c-0", os.O_RDWR, 0666)
- if err != nil {
- return
- }
- defer f.Close()
- if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, f.Fd(), 0x0703, uintptr(addr), 0, 0, 0); err != 0 {
- return
- }
- _, err = f.Write([]byte{0x24, 0x00})
- if err != nil {
- return
- }
- time.Sleep(15500 * time.Microsecond)
- const blockSize = 3
- data := make([]struct {
- Data [2]byte
- CRC byte
- }, 2)
- buf1 := make([]byte, 6)
- _, err = f.Read(buf1)
- if err != nil {
- return
- }
- buf := bytes.NewBuffer(buf1)
- err = binary.Read(buf, binary.BigEndian, data)
- if err != nil {
- return
- }
- var results []uint16
- for i := 0; i < 2; i++ {
- calcCRC := calcCRC_SHT3X(0xFF, data[i].Data[:2])
- crc := data[i].CRC
- if calcCRC != crc {
- return
- }
- results = append(results, getU16BE(data[i].Data[:2]))
- }
- temp = fmt.Sprintf("%.2f", float64(results[0])*175/(0x10000-1)-45)
- hum = fmt.Sprintf("%.2f", float64(results[1])*100/(0x10000-1))
- return
- }
- func calcCRC_SHT3X(seed byte, buf []byte) byte {
- for i := 0; i < len(buf); i++ {
- seed ^= buf[i]
- for j := 0; j < 8; j++ {
- if seed&0x80 != 0 {
- seed <<= 1
- seed ^= 0x31
- } else {
- seed <<= 1
- }
- }
- }
- return seed
- }
- func getU16BE(buf []byte) uint16 {
- v := uint16(buf[0])<<8 + uint16(buf[1])
- return v
- }
复制代码 |
|