本文介绍了写多个保持寄存器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过下面的代码写一个保持寄存器(16位)。但是我没有成功。 '超时'例外发生。请告诉我我错在哪里。

代码如下。







I want to write a holding register(16 bit) by below code.but i have not got success. 'Time out' exception occures. Please suggest me where i am wrong.
Code is given below.



byte address = Convert.ToByte("127");
                ushort start = Convert.ToUInt16("15");
                short[] value = new short[1];
                value[0] = Convert.ToInt16("1");

                try
                {
                    while (!mb.SendFc16(address, start, (ushort)1, value)) ;
                }
                catch (Exception err)
                {
                    lblConfigurationBlockStatus.Text= err.Message;
                }
                lblConfigurationBlockStatus.Text=(mb.modbusStatus);










public bool SendFc16(byte address, ushort start, ushort registers, short[] values)
       {
           //Ensure port is open:
           if (sp.IsOpen)
           {
               //Clear in/out buffers:
               sp.DiscardOutBuffer();
               sp.DiscardInBuffer();
               //Message is 1 addr + 1 fcn + 2 start + 2 reg + 1 count + 2 * reg vals + 2 CRC
               byte[] message = new byte[9 + 2 * registers];
               //Function 16 response is fixed at 8 bytes
               byte[] response = new byte[8];

               //Add bytecount to message:
               message[6] = (byte)(registers * 2);
               //Put write values into message prior to sending:
               for (int i = 0; i < registers; i++)
               {
                   message[7 + 2 * i] = (byte)(values[i] >> 8);
                   message[8 + 2 * i] = (byte)(values[i]);
               }
               //Build outgoing message:
               BuildMessage(address, (byte)16, start, registers, ref message);

               //Send Modbus message to Serial Port:
               try
               {
                   sp.Write(message, 0, message.Length);
                   GetResponse(ref response);
               }
               catch (Exception err)
               {
                   modbusStatus = "Error in write event: " + err.Message;
                   return false;
               }
               //Evaluate message:
               if (CheckResponse(response))
               {
                   modbusStatus = "Write successful";
                   return true;
               }
               else
               {
                   modbusStatus = "CRC error";
                   return false;
               }
           }
           else
           {
               modbusStatus = "Serial port not open";
               return false;
           }
       }

推荐答案

try
    {
    int retries = 3;
    while (!mb.SendFc16(address, start, (ushort)1, value))
        {
        if (--retries == 0) break;
        }
    }


这篇关于写多个保持寄存器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 06:33