Skip to content

Instantly share code, notes, and snippets.

@analogic
Created September 15, 2020 13:27
Show Gist options
  • Save analogic/666b7c2a285adc38db0984e03041d56c to your computer and use it in GitHub Desktop.
Save analogic/666b7c2a285adc38db0984e03041d56c to your computer and use it in GitHub Desktop.
Hongyuv ultrasonic anemometer + RPI RS486 HAT
package main
import (
"bytes"
"encoding/binary"
"fmt"
"time"
)
import "github.com/goburrow/modbus"
func main() {
fmt.Println("Starting...")
handler := modbus.NewRTUClientHandler("/dev/ttyAMA0")
handler.BaudRate = 9600
handler.DataBits = 8
handler.Parity = "E"
handler.StopBits = 1
handler.SlaveId = 1
handler.Timeout = 5 * time.Second
// handler.Logger = log.New(os.Stdout, "mb: ", log.Lshortfile)
if err := handler.Connect(); err != nil {
panic("RS485 error conecting: " + err.Error())
}
fmt.Println("RS485 initialized...")
//...
for true {
client := modbus.NewClient(handler)
results, err := client.ReadHoldingRegisters(0, 41)
if err != nil {
panic("RS485 error reading modbus: " + err.Error())
}
var response struct {
Id uint16
Direction uint16
Speed float32
}
// some weird chinese float encoding flipping, we are fixing that
l1 := results[6]
l2 := results[7]
results[6] = results[4]
results[7] = results[5]
results[4] = l1
results[5] = l2
// end of weird chinese trickery
reader := bytes.NewReader(results)
if err := binary.Read(reader, binary.BigEndian, &response); err != nil {
panic("binary.Read failed:" + err.Error())
}
// fmt.Print("ID: ")
// fmt.Println(response.Id)
fmt.Print(time.Now().Format(time.RFC3339))
fmt.Print(" direction: ")
fmt.Print(response.Direction)
fmt.Print(", speed: ")
fmt.Println(response.Speed)
time.Sleep(time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment