golang modbus tcp
时间: 2023-08-22 20:11:05 浏览: 57
In Golang, you can use various libraries to implement Modbus TCP communication. One popular library is "github.com/goburrow/modbus". Here's a simple example of using this library to communicate with a Modbus TCP device:
```go
package main
import (
"fmt"
"log"
"github.com/goburrow/modbus"
)
func main() {
// Create a TCP connection to the Modbus device
handler := modbus.NewTCPClientHandler("192.168.1.1:502") // replace with your device's IP address and port
err := handler.Connect()
if err != nil {
log.Fatal(err)
}
defer handler.Close()
// Create a new Modbus client
client := modbus.NewClient(handler)
// Read holding registers from address 0 to 10
results, err := client.ReadHoldingRegisters(0, 10)
if err != nil {
log.Fatal(err)
}
// Print the values
for i, value := range results {
fmt.Printf("Register %d: %v\n", i, value)
}
}
```
Make sure to replace "192.168.1.1:502" with the actual IP address and port of your Modbus TCP device. This example demonstrates how to read holding registers, but you can also write to coils or other types of Modbus data.
Remember to import the "github.com/goburrow/modbus" package in your project. You can do this by running `go get github.com/goburrow/modbus` in your terminal.
I hope this helps you get started with Modbus TCP communication in Golang! Let me know if you have any further questions.