simonvetter / modbus

Go modbus stack (client and server)
MIT License
262 stars 83 forks source link

Multiple devices #5

Closed rtm7777 closed 2 years ago

rtm7777 commented 2 years ago

Hello,

I have 3 modbus devices (RTU) and I want to read all of them on each iteration. what is the best approach for this? should I client.SetUnitId(ID) before every call?

Thanks!

simonvetter commented 2 years ago

Sure, use SetUnitId() to change the target slave before calling ReadRegisters() like so:

    // select the first sensor at address 0x10
    client.SetUnitId(0x10)

    // read two 16-bit holding registers at address 0x4000
    regs, err = client.ReadRegisters(0x4000, 2, modbus.HOLDING_REGISTER)
    if err != nil {
        fmt.Printf("failed to read registers 0x4000 and 0x4001: %v\n", err)
    } else {
        fmt.Printf("register 0x4000: 0x%04x\n", regs[0])
        fmt.Printf("register 0x4001: 0x%04x\n", regs[1])
    }

    // select the 2nd sensor at address 0x20
    client.SetUnitId(0x20)

    // read two 16-bit holding registers at address 0x4000
    regs, err = client.ReadRegisters(0x4000, 2, modbus.HOLDING_REGISTER)
    if err != nil {
        fmt.Printf("failed to read registers 0x4000 and 0x4001: %v\n", err)
    } else {
        fmt.Printf("register 0x4000: 0x%04x\n", regs[0])
        fmt.Printf("register 0x4001: 0x%04x\n", regs[1])
    }

If the sensors are all the same you might as well do it in a loop.