golang---modbus TCP通信

第三方库

"github.com/goburrow/modbus"
//start:起始寄存器
//quantity一共要读几个寄存器
func getDataByModBus(addr, port string, start, quantity int) {
	// 创建TCP连接
	handler := modbus.NewTCPClientHandler(addr + ":" + port)
	handler.Timeout = 10 * time.Second
	handler.SlaveId = 1

	err := handler.Connect()
	if err != nil {
		panic(err)
	}
	defer handler.Close()

	// 创建Modbus客户端
	client := modbus.NewClient(handler)

	// 读取寄存器数据
	results, err := client.ReadHoldingRegisters(uint16(start), uint16(quantity))
	if err != nil {
		panic(err)
	}

	// 输出读取的数据
	fmt.Println(results)
	f := 0
	for i := 0; i <= len(results)-1; i += 2 {
		if i <= 19 {
			v := float64(int(results[i])*256 + int(results[i+1]))
			fmt.Printf("0-19寄存器%d---%#v--%#v ==== %#v \n", f, results[i], results[i+1], v)
			f += 1
			continue
		}
		if i >= 20 && i <= 39 {
			v := float64(int(results[i])*256+int(results[i+1])) / float64(100)
			fmt.Printf("20-39寄存器%d---%#v--%#v ==== %#v \n", f, results[i], results[i+1], v)
			f += 1
			continue
		}
		if i >= 40 && i <= 45 {
			v := float64(int(results[i])*256+int(results[i+1])) / float64(100)
			fmt.Printf("40-45寄存器%d---%#v--%#v ==== %#v \n", f, results[i], results[i+1], v)
			f += 1
			continue
		}
		if i >= 46 && i <= 47 {
			v := float64(int(results[i])*256 + int(results[i+1]))
			fmt.Printf("寄存器%d---%#v--%#v ==== %#v \n", f, results[i], results[i+1], v)
			f += 1
			continue
		}
		if i >= 48 && i <= 49 {
			v := float64(int(results[i])*256+int(results[i+1])) / float64(100)
			fmt.Printf("寄存器%d---%#v--%#v ==== %#v \n", f, results[i], results[i+1], v)
			f += 1
		}
	}
}

你可能感兴趣的:(Golang,golang,tcp/ip)