C # development Modbus RTU client Modbus test Demo,modbus serial communication, virtual Modbus-rtu test

Source: Internet
Author: User
Tags array length

Preface

This article will use a NuGet exposed component technology to implement a Modbus RTU client, easy to read and write to the Modbus RTU server, this server can be a computer-side C # design, can also be implemented by the PLC, or any other server to support this communication protocol.

GitHub Address: Https://github.com/dathlin/HslCommunication If you like star or fork, you can also enjoy support.

You can download the installation in the NuGet Manager in Visual Studio, or you can enter the following instructions directly in the NuGet console to install:

Install-package hslcommunication

NuGet Installation Tutorial Http://www.cnblogs.com/dathlin/p/7705014.html

Technical Support QQ Group: 592132877 (Component version update details will be released in the group first) Component API address: http://www.cnblogs.com/dathlin/p/7703805.html

Special thanks
    • Netizen: Chen Enfu to float,int data reading test, only fixed the bug that the weight bit is reversed.
    • Netizen:U4 happy snail found a wrong method name on the blog, updated on January 8, 2018 13:34:39. and feedback some special equipment (Modbus TCP server) to read the data of the bug. has been fixed.

Just talk.

The design pattern here is the client actively requests the server data, then receives the server's feedback data, supports the native instruction to send and receive, supports some other convenient API to send and receive. The special function code needs to use the native send and receive API, this component supports the following function operation:

    • 0x01 reads the operation of the coil,
    • 0X02 read discrete operations,
    • 0x03 the value of the read register,
    • 0x05 Write a coil operation,
    • 0X06 Write a register value,
    • 0x0F Bulk Write Coil operation,
    • 0x10 Bulk Write Register value,

If your device needs data outside of these features, you can use the native API method, but the premise of this method is that you are very clear about the Modbus protocol, if you do not understand this protocol, you can refer to the following blog description:

http://blog.csdn.net/thebestleo/article/details/52269999

If you need to build your own Modbus server, you can refer to this article: http://www.cnblogs.com/dathlin/p/7782315.html

Accessing test projects

Need to download a serial-port virtual software

Virtual Serial Port Driver

: https://virtual-serial-port-driver.en.softonic.com/

Then virtualize two serial ports out, COM4, COM5 by default is connected together. So we can do the local tests.

Before you develop your own client program, you can test with the Modbus test tool, an open source project at the following address is the Modbus RTU test tool developed based on this component, which can be directly used for reading and writing tests.

modbustcpserver.zip Start the service first and then start the serial port

The following project is an Access test project for this component, you can perform a preliminary access test, eliminating the hassle of writing your test program, which is written with the access of Mitsubishi, Siemens PLC. Can be referenced at the same time.

is:hslcommunicationdemo.zip

Reference

ModBus components all the function classes are in the Hslcommunication.modbus namespace, so before you use Add

Using hslcommunication.modbus;using hslcommunication;

  

How to use

Instantiation:

You must instantiate before you can use read-write functionality:

Private Modbusrtu busrtuclient = new Modbusrtu (station);

Note: In the Modbus server device, most of the devices are starting from address 0, some special devices are starting from address 1, so this component, the default starting from address 0, if you want to start from address 1, then you need the following configuration:

Busrtuclient.addressstartwithzero = False;

Then the next need to initialize the parameters, for the serial port, the usual parameters are the serial port name, baud rate, data bit, stop bit, check bit, provides a way to set a delegate

            Try            {                Busrtuclient.serialportinni (sp = = sp)                     . PortName = "COM5";                     Sp. baudrate = 9600;                     Sp. DataBits = 8;                     Sp. StopBits = System.IO.Ports.StopBits.One;                     Sp. Parity = System.IO.Ports.Parity.None;                 } );                Busrtuclient.open (); Open            }            catch (Exception ex)            {                MessageBox.Show (ex). Message);            }

If you close, call the following method

Busrtuclient.close ();

The following code demonstrates commonly used read and write operations, for the sake of convenience, no longer judge Issuccess, is generally successful:

        private void Userbutton30_click (object sender, EventArgs e) {//read operation bool coil100 = Busrtuclient.readcoil ("100").   Content; Read the coil 100 on-off short short100 = busrtuclient.readint16 ("100"). Content; Read the short value of register 100 ushort ushort100 = busrtuclient.readuint16 ("100"). Content; Read the ushort value of register 100 int int100 = Busrtuclient.readint32 ("100").      Content; Read the int value of register 100-101 UINT uint100 = Busrtuclient.readuint32 ("100").   Content; Read the UINT value of register 100-101 float float100 = busrtuclient.readfloat ("100"). Content; Read the float value of register 100-101 long long100 = Busrtuclient.readint64 ("100").    Content; Read the Long value of register 100-103 ulong ulong100 = Busrtuclient.readuint64 ("100"). Content; Read the ULONG value of register 100-103 double double100 = busrtuclient.readdouble ("100"). Content; Read the Double value of register 100-103 string str100 = busrtuclient.readstring ("100", 5). content;//read 100 to 104 a total of 10 characters in a string//write Operation Busrtuclient.writecoil ("+", true);//write Coil 100 for Busrtuclient.write ("+", (short) 12345);//write into register 100 is 12345 busrtuclient.write ("", (ushort) 45678);//write Register 100 is 45678 busrtuclient.write ("100", 1            23456789);//write Register 100-101 is 123456789 busrtuclient.write ("", (UINT) 123456778);//write register 100-101 is 123456778 Busrtuclient.write ("100", 123.456);//write Register 100-101 for 123.456 busrtuclient.write ("12312312312414L");//write Register 100-103 is a big data busrtuclient.write ("12634534534543656UL");//write Register 100-103 is a big data busrtuclient.w                    Rite ("123.456d");//write Register 100-103 for a double-precision data busrtuclient.write ("", "K123456789"); }

The following are the strict operation, as well as the bulk of the complex read and write operations, if you want to read 1000 m, 1000 times to read the loop can take 3 seconds, if the following batch read, only need 50ms, but you need to be familiar with the principle of the byte to handle

Read Coil API:

Here, for example, read the number of coils with an address of 0 and a length of 10, the data read has been automatically converted into a bool array, convenient two times processing:

        private void Userbutton8_click (Object Sender,eventargs e)        {            hslcommunication.operateresult<bool[]> Read = Busrtuclient.readcoil ("0", ten);            if (read. issuccess)            {                bool coil_0 = read. CONTENT[0];                BOOL Coil_1 = read. CONTENT[1];                BOOL coil_2 = read. CONTENT[2];                BOOL Coil_3 = read. CONTENT[3];                BOOL Coil_4 = read. CONTENT[4];                BOOL Coil_5 = read. CONTENT[5];                BOOL Coil_6 = read. CONTENT[6];                BOOL coil_7 = read. CONTENT[7];                BOOL Coil_8 = read. CONTENT[8];                BOOL Coil_9 = read. CONTENT[9];            }            else            {                MessageBox.Show (read. Tomessageshowstring ());            }        }

Of course, you can also use the Data Transformation API provided by the component to achieve data extraction:

To read discrete data:

The code that reads the discrete data and reads the coils is almost identical, and the processing is consistent, but the method name is changed to:

        private void Userbutton8_click (Object Sender,eventargs e)        {            hslcommunication.operateresult<bool[]> Read = Busrtuclient.readdiscrete ("0", ten);            if (read. issuccess)            {                bool coil_0 = read. CONTENT[0];                BOOL Coil_1 = read. CONTENT[1];                BOOL coil_2 = read. CONTENT[2];                BOOL Coil_3 = read. CONTENT[3];                BOOL Coil_4 = read. CONTENT[4];                BOOL Coil_5 = read. CONTENT[5];                BOOL Coil_6 = read. CONTENT[6];                BOOL coil_7 = read. CONTENT[7];                BOOL Coil_8 = read. CONTENT[8];                BOOL Coil_9 = read. CONTENT[9];            }            else            {                MessageBox.Show (read. Tomessageshowstring ());            }        }

Read the Register data:

  Suppose we need to read data with an address of 0 and a length of 10, which is 10 data, 2 bytes per data, and a total of 20 bytes of data. Before parsing the data, let's assume that you can refer to the following parsing

before parsing your own data.

        private void Userbutton10_click (object sender, EventArgs e) {hslcommunication.operateresult<            byte[]> read = Busrtuclient.read ("0", 10); if (read. issuccess) {//A total of 20 bytes, 2 bytes per data, high in front, low in the back//Before data parsing need to know what kind of data is stored inside, so some assumptions need to be made ://The first two bytes are the short data type short value1 = busTcpClient.ByteTransform.TransInt16 (read.                 Content, 0); The next 2 bytes are ushort type ushort value2 = busTcpClient.ByteTransform.TransUInt16 (read.                 Content, 2); The next 4 bytes are int type int value3 = BusTcpClient.ByteTransform.TransInt32 (read.                 Content, 4); The next 4 bytes are float type float value4 = busTcpClient.ByteTransform.TransFloat (read.                 Content, 8); The next total byte, a total of 8 bytes, is the specification information string speci = Encoding.ASCII.GetString (read.                Content, 12, 8); All data has been extracted} else {MEssagebox.show (read.            Tomessageshowstring ()); }        }

Write a coil:

Write a coil, this is relatively simple, suppose we need to write the coil 0, for the pass

        private void Userbutton11_click (object sender, EventArgs e)        {            Hslcommunication.operateresult write = Busrtuclient.writecoil ("0", true);            if (write. issuccess)            {                //write succeeded                TextBox1.Text = "Write succeeded";            }            else            {                MessageBox.Show (write. Tomessageshowstring ());            }        }

Write a register:

It is also very convenient to write a register, which provides three overloaded methods that allow three ways to write: Write separately, short,ushort,byte three kinds:

        private void Userbutton12_click (object sender, EventArgs e)        {short            value = -1234;            Hslcommunication.operateresult write = Busrtuclient.writeoneregister ("0", value);            if (write. issuccess)            {                //write succeeded                TextBox1.Text = "Write succeeded";            }            else            {                MessageBox.Show (write. Tomessageshowstring ());            }        }

  

        private void Userbutton12_click (object sender, EventArgs e)        {            ushort value = 56713;            Hslcommunication.operateresult write = Busrtuclient.writeoneregister ("0", value);            if (write. issuccess)            {                //write succeeded                TextBox1.Text = "Write succeeded";            }            else            {                MessageBox.Show (write. Tomessageshowstring ());            }        }

  

        private void Userbutton12_click (object sender, EventArgs e)        {            //0x00 is high, 0x10 is low            Hslcommunication.operateresult write = Busrtuclient.writeoneregister ("0", 0x00, 0x10);            if (write. issuccess)            {                //write succeeded                TextBox1.Text = "Write succeeded";            }            else            {                MessageBox.Show (write. Tomessageshowstring ());            }        }

Bulk Write Coils:

private void Userbutton13_click (object sender, EventArgs e)        {            //Coil 0 is true, coil 1 is false, coil 2 is true .... And so on, and so on, how much is the array length, and how many coils are written            bool[] value = new bool[] {true, False, True, True, False, false};            Hslcommunication.operateresult write = Busrtuclient.writecoil ("0", value);            if (write. issuccess)            {                //write succeeded                TextBox1.Text = "Write succeeded";            }            else            {                MessageBox.Show (write. Tomessageshowstring ());            }        }

  

Bulk Write Registers:

The first case is written to a short array, which is relatively simple:

        private void Userbutton14_click (object sender, EventArgs e)        {            short[] value = new short[] { -1234, 467, 12345};
   hslcommunication.operateresult write = Busrtuclient.write ("0", value);            if (write. issuccess)            {                //write succeeded                TextBox1.Text = "Write succeeded";            }            else            {                MessageBox.Show (write. Tomessageshowstring ());            }        }

The second case is to write a string of ushort arrays, which is also relatively simple:

        private void Userbutton14_click (object sender, EventArgs e)        {            ushort[] value = new ushort[] {46789, 467, 12345};            Hslcommunication.operateresult write = Busrtuclient.write ("0", value);            if (write. issuccess)            {                //write succeeded                TextBox1.Text = "Write succeeded";            }            else            {                MessageBox.Show (write. Tomessageshowstring ());            }        }

The more complicated is to write custom data, according to the above read register, such as I need to write to register 0, register 1 together an int data, then we write:

        private void Userbutton15_click (object sender, EventArgs e)        {            int value = 12345678;//a data            waiting to be written Hslcommunication.operateresult write = Busrtuclient.write ("0", value);            if (write. issuccess)            {                //write succeeded                TextBox1.Text = "Write succeeded";            }            else            {                MessageBox.Show (write. Tomessageshowstring ());            }        }

Other data refer to this on the line, if you do not understand, you can contact the QQ group above.

Data manipulation, using native messages to manipulate data:

Pass in a byte array, the data content is consistent with the original data, for example, I want to read the register address of 0, the length of 3 of the data through the native API, then the byte hex is identified as 01 03 00 00 00 03 does not include CRC check code

        private void Button26_click (object sender, EventArgs e)        {            try            {                operateresult<byte[]> read = Busrtuclient.readbase (HslCommunication.Serial.SoftCRC16.CRC16 ( ("HslCommunication.BasicFramework.SoftBasic.HexStringToBytes"));                if (read. issuccess)                {                    textbox11.text = "Result:" + HslCommunication.BasicFramework.SoftBasic.ByteToHexString (read. Content, ');                }                else                {                    MessageBox.Show ("Read failed:" + read. Tomessageshowstring ());                }            }            catch (Exception ex)            {                MessageBox.Show ("Read failed:" + ex.) Message);            }        }

The above code in the operation with a conversion mechanism, the input is 16 binary text, converted to byte[] data, the middle of the separator can be a space, can be '-', can also be ', ', ' _ ' and so on, and so on, called the component-based data conversion function.

C # development Modbus RTU client Modbus test Demo,modbus serial communication, virtual Modbus-rtu test

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.