Federico Pinciaroli
Federico Pinciaroli

Reputation: 163

C# Modbus SlaveException reading registry

I'm working on a c# project Which have to comunicate with PLC by TCP Modbus. I'm using Nmodbus Library and it works fine. The problem is when I try to read/write Registry over 12000. I get this exception:

  Exception 'Modbus.SlaveException'  Function Code: 131

This is the part of the code which generates the exception:

private TcpClient tcpClient;
     private ModbusIpMaster master;
     private void connect(){
    // connect to Modbus TCP Server
    string ipAddress = "192.168.77.7"; //Input WISE IP
    int tcpPort = 502;
    tcpClient = new TcpClient(ipAddress, tcpPort);

    // create Modbus TCP Master by the tcp client
    master = ModbusIpMaster.CreateIp(tcpClient);

    // rewrite the value of AO ch0 (40020~40021) by float
    byte slaveID = 1;
   // ushort rewriteAddress = 20;
   // ushort[] rewriteValue = new ushort[2] { 0, 0 };
   // float[] floatData = new float[1] { 223.456F };
   // Buffer.BlockCopy(floatData, 0, rewriteValue, 0, 4);
    Random random = new Random();

    // read the holding register 12001~12005 
    // write the holding register 301~305

    ushort startAddress = 12000;
    ushort numOfPoints = 5;
    master.Transport.ReadTimeout = 1000;
    while (!_shouldStop1)
    {
        try
        {
            ushort[] register = master.ReadHoldingRegisters(slaveID, startAddress, numOfPoints);

            for (int index = 0; index <register.Length; index++)
            {
                Console.WriteLine(string.Format("AO[{0}] = {1}", index,register[index]));
            }

            for (ushort index = 0; index < 4; index++)
            {
                master.WriteSingleRegister(slaveID, (ushort)(301 + index),(ushort) data[index]);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Any suggestion will be appreciated. Thanks, Federico.

Upvotes: 2

Views: 3740

Answers (1)

Hassan Akhtar
Hassan Akhtar

Reputation: 1

I know this is an old question, replying because may be useful for new users. holding registers start from 40001, but when we read holding registers in many cases we remove 4 from start mean address of 40001 will be only '1'. holding registers are only 16bit but mostly values are 32 bit so now you can use following code: address of holding register can vary according to the field device, please read its technical manual in detail for registers. uint[] registers = new uint[5]; registers = await master.ReadHoldingRegisters32Async(slaveId, RegisterNo, TotalRegisters);

keep it mind it will return back unit data type, then you can convert it to decimal/float or string as per requirement.

Upvotes: 0

Related Questions