Home / C# / Modbus with C#: libraries, code, utilities and examples

Modbus with C#: libraries, code, utilities and examples

In this post you will find how to use nModbus with C# and how to create a simulation enviroment to test your program with Modbus.
Other useful resources that you can find in this post are:

  • using a Modbus simulator
  • Creating virtual Com ports
  • Using sniffer tools to debug the transmission
  • A Modbus TCP Client in C# with another library

Getting NModbus

The C# library I use the most when I need Modbus communication between pc and plcs or other components is nModbus.
nModbus manages both Modbus TCP and RTU protocols, it’s well tested and sources are available.
The new NModbus4 library on GitHub, but to compile it you need Visual Studio 2015, due to some C# 6 features used.
You can also download from NuGet by searching for NModbus4.
NModbus4

The old library on google code has bugs (check comments for more informations), please consider using either the new NModbus4 library, or you can download the old code from this repository: https://github.com/mesta1/nmodbus.
The old library of nModbus is http://code.google.com/p/nmodbus/and here you can get the latest sources.

Once you extract the sources you can open the solution file, located in the src folder.

Sample code

NModbus contains many samples included in the source code. Once you open it, you can go to MySample project that contains many examples on how to read and write using different devices. You can check a how-to video here: https://www.mesta-automation.com/modbus-with-c-an-how-to-video/

The two examples that I use the most are Modbus TCP and RTU, and an example of the code to use the library is this:

Modbus TCP

/*
 *  Reading
 */
TcpClient client = new TcpClient("127.0.0.1", 502);
ModbusIpMaster master = ModbusIpMaster.CreateIp(client);

// read five input values
ushort startAddress = 100;
ushort numInputs = 5;
bool[] inputs = master.ReadInputs(startAddress, numInputs);

for (int i = 0; i < numInputs; i++)
	Console.WriteLine("Input {0}={1}", startAddress + i, inputs[i] ? 1 : 0);

/*
 *  Writing
 */
ushort startAddress = 1;
// write three coils
master.WriteMultipleCoils(startAddress, new bool[] { true, false, true });

Modbus RTU


SerialPort port = new SerialPort("COM1");

// configure serial port
port.BaudRate = 9600;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.Open();

// create modbus master
IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

byte slaveId = 1;
ushort startAddress = 1;
ushort numRegisters = 5;

// read five registers
ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);

for (int i = 0; i < numRegisters; i++)
	Console.WriteLine("Register {0}={1}", startAddress + i, registers[i]);

byte slaveId = 1;
ushort startAddress = 1;

// write three coils
master.WriteMultipleCoils(slaveId, startAddress, new bool[] { true, false, true });

Depending on the registers that you are going to read and write you have different methods, that will call different functions of the protocol, and that will return the results in 2 formats: ushort or bool (if you are reading multiple registers you will get array of ushorts and bools).

ITDONOTWORK

NModbus is supported by thousands of users, and you can find help on the NModbus google Group.

Testing your program with a simulation:

The most common Modbus simulator is located at http://www.plcsimulator.org/

This simulator provides both Modbus TCP and RTU protocols, and shows the content of the registers in the main windows so you can analyze the behaviour of your program directly in the tables of the simulator.

Creating Virtual COM Ports to test Modbus RTU:

While it’s easy to use TCP to analyze the Modbus TCP on the host (just create a socket with a 127.0.0.1 ip), testing Modbus RTU or ASCII may require some hardware, like a null-modem cable and 2 COM Ports.
To avoid this you can download a null modem emulator called Com0Com (open source, located at http://sourceforge.net/projects/com0com/) to create a pair of virtual com ports which you can use to connect your simulator and software.

Sniffer tools available for free:

If you need to analyze the traffic between two devices to see what’s going on with your communication, there are two useful tools:
Wireshark is used to sniff ethernet packets and to decode the protocol. This tool can decode Modbus TCP protocol quite well and it’s also useful to debug the transmission.
Free Serial Port Monitor is a serial port sniffer that can analyze the transmission between 2 COM Ports.

Other Modbus TCP libraries:

While NModbus is the best choice, another Modbus TCP library is available at http://www.codeproject.com/Articles/16260/Modbus-TCP-class

This library provides a client with some interesting features and it’s also useful for debugging the devices.

How-to video on NModbus

You can get the software configuration in the article.

179 comments

  1. Great article, are you familiar enough with NModbus (or the modbus protocol in general) to know if it has the ability to be event-driven. That is, to not have to user a timer or manually poll for data from a client PLC?

    I know an OPC Server is the ideal solution, but for only a couple PLCs, it’s too expensive.

    Finally, I know that the NModbus site was hacked and the documentation was lost. However, the author said the documentation could be recovered if rebuilt from the Nant task in the source code. (https://groups.google.com/d/topic/NModbus-discuss/BfQz-po8OiM/discussion) Perhaps you could re-host the documentation, or that could be another article! I know a LOT of developers are looking for it.

    Cheers and keep up the good work

  2. Hi Derek, there are no problem in hosting the documentation of nmodbus, but it just consists in 8 examples that can be found inside the source code (“MySample” folder).
    About the event-driven communication, it’s just a layer above the syncronous communication.
    To develop an asyncronous communication you need to have a thread dedicated to polling the modbus device. This thread listen to external calls from the application and executes reads and writes to the plc. When data are ready it fires a “DataReady_Event(EventArg data)” to all subscribers.
    The problem of this architecture is that it requires a lot of code that add no value to the application itself, because once you can write a multithreaded application, you can just extract your data from the communication thread, saving yourself from the pain of event-handling, subscription and memory leaks. There is an example of hmi in my last article that shows a basic structure of multithreaded app.

  3. Great article and blog! Thank you for sharing all this information, it’s very appreciated!

    Cheers!

  4. Hi, I’ve problem using nmodbus library with plcsimulator. When i’m trying to read data in intervals ~10sec, all slots in simulator becoming full in 10 secconds.

    I don’t know if it’s problem with code or simulator ( refreshing is not fast enought) ?

    Maybe someone had this problem ?

  5. Never had problems with plc simulator. Probably you need to check the plc simulator configuration, or to check with a sniffer what packets you are sending and receiving.
    There are some videos on youtube on how to use wireshark, if you are using modbus tcp.

  6. Hello.

    Your library is great and many thanks for share it.
    I have one question about using your library.
    When I configure the serial port with a wrong Baudrate the code block because the stream don’t receive the expetc number of bytes.
    You don’t have the Timeout funcionalitie implemented or I’m missing something?

    Best regards, and thanks again

    • Hello again.
      The solution is simple and is implemented.
      My mistake.

      To use Timeout communication, just have to configure the Serial port ReadTimeout and WriteTimeout, like this:

      port.ReadTimeout = 1000; //1 second
      port.WriteTimeout = 1000; //1 second

      Best regards

  7. Hi,

    I’d like to rephrase Dereks question above regarding event-driven. I stumbled upon S7.net (originally hosted at: http://s7net.codeplex.com/ which is dedicated for Siemens PLC and is now continued at: https://github.com/killnine/s7netplus

    I belive this library uses modbus (but not sure). However it also lacks the event driven communication. I understand that you can create a thread that polls the PLC and generates the event when it detects that data is changed. However the optimal solution would be that the PLC (or modbus device) sends the data itself upon change. Does such mechanism exist for the modbus protocol?

    • Hello.

      If your PLC (or another modbus device ) is a master, so your PC application will be a slave. In this case the PLC(master) can share is information when ready to do it, and the PC(slave) only have to receive it.

      The NModbus supports this “kind of feature”, it can be configured as Slave or Master (ASCII, TRU and TCP/IP).

      I think you must read something about the Modbus Protocol first. The Modbus protocol is very simple to understand, so you don’t need so much time to do it.
      After that you will use the NModbus library mutch better.
      (sorry for my bad english 🙂 )

      Best regards

      • Hi,

        Thanks for your answer. I Read about the protocol for about 5 minutes now 🙂

        So from what I understand you have a master and a slave configuration. The master sends out requests which the slave node(s) reply to. Typically a polling scenario. In order to get data upon events I have to set up the PLC as a master which writes to the PC as a slave. This would require some kind of extra logic (PLC program) set up in the PLC which I want to supervise. With TCP-modbus it is possible to setup the PC and PLC as both master and slave (on different connections). Not the general simple solution I was looking for so I think if I want an event driven communication it’s better to go with some OPC-solution which has already solved what I’m looking for.

        Do you know how this is solved under the hood of the OPC-server? Is the OPC server polling the device?

        • Hi Eric, probably you are confusing the two libraries, but S7.Net use S7 protocol, nModbus use Modbus protocol (that depending on the physical cable can be Modbus TCP (ethernet) or Modbus RTU (RS 422 – RS 485).
          S7.Net use Profinet (or Industrial Ethernet, don’t remember that good) and it’s derived from LibNoDave that can communicate both with Profinet and MPI.
          To use nModbus you need to add the Modbus libraries to the plc program.
          About Master and Slave, think like internet: a website is the Master and your pc that browse the site is the Slave.
          The master choose who and when a slave can talk, but it’s up to the slave to choose what he needs from the master, so you need no extra-coding on the plc part if you just need to read/write values on a DB.
          Both MPI, Profibus and Profinet are multi-master protocols, this means that when a master did what he needs, he pass the token to the other master, and so on.
          Modbus RTU is not multi-master, Modbus TCP is multi-master.
          About S7.Net, you can check a working hardware configuration sample in this thread:
          https://www.mesta-automation.com/nettoplcsim-how-to-connect-step-7-plc-sim-to-scadas/
          this has been tested.
          About the event-driven architecture:
          or you implement your own in your polling thread, or you use it as is with an OPC Server.

      • Hello again,

        I’m greatful that you are answering my newbie questions. The background for the question is that I found the S7.net library. Tried it and worked well. Since there are no real support for this library I wanted to find more information regarding how it worked under the hood (which protocol was used and so on). I found this discussion:

        https://github.com/killnine/s7netplus/issues/3

        Which to me indicated that the library used modbus TCP for communication. I kind of doubt that it is derived from LibNoDave after reading this discussion:

        http://www.plctalk.net/qanda/showthread.php?t=65768

        And by looking at the source it seems like it’s really implemented in C# all the way down to the byte communication. But it may very well use another protocol than modbus and I’m quite eager to find out which protocol. We did not set up anything (if I remeber correctly) on the PLC side to be able to access it using S7.net

        • Hi Eric, the protocol is a reverse engineering of the s7 protocol used by Step7.
          A similar code can be found inside libnodave and also inside prodave, the official Siemens library.
          I was wrong about S7.net, because the project that is derived from libnodave is Siemens plc toolbox.
          http://siemensplctoolboxlib.codeplex.com/releases
          This is more dvanced than S7.net.

  8. I think this may be the best article to start with modbus, really nice work.

  9. Vanderley Maia

    Hi Mesta, thank you so much for your help!

    unfortunately I’m having problems with my device and not getting the values that I would like to read.
    I have always a timeout problem. :/

    This is my code:

    private void button1_Click(object sender, EventArgs e)
    {
    // create modbus master
    IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(PortaEmulada1);
    ushort[] registers = master.ReadHoldingRegisters((byte)1, 80, 2);
    }

    The device that I’m trying use is this:
    http://www.ciberdobrasil.com.br/pdf/mp_upd200.pdf

    Do you have any idea that what is happning?

    Thank you for your great work!
    Best regards!

    • Problem solved guys.

      Basically the problem was that my device CIBER needs that you set the Date Terminal Ready parameters as TRUE. After that, the protocol works just perfectly 😀

      Thank you for your wonderfull work Mesta.
      Best regards.

    • Vanderley Maia

      Problem solved guys.

      Basically the problem was that my device CIBER needs that you set the Date Terminal Ready parameters as TRUE. After that, the protocol works just perfectly

      Thank you for your wonderfull work Mesta.
      Best regards.

  10. Hello Mesta,

    I have very little knowledge of this field and your articles have given me great information.

    For one project, I want to control a servo motor/drive (Delta ASDA B2) though c# program. I want the motor to be controlled directly through the software code using Modbus/RS 232. The drive supports both protocols. I do not want to use a PLC. Is it possible? Please advise.

    Best Regards and thanks a lot for such a nice work.

    • Yes you can use C# and NModbus to control your drive, if the serial port is a RS232. If it is a RS422 or 485 you need extra-hardware.
      To communicate with Modbus through the serial port you need the Modbus RTU protocol, already included inside NModbus.
      You just have to know what register you need to read/write, and write the values that you need.
      Probably you need to do this independently if you use a PLC or a PC.
      However It is reccomended to use real-time OS to control motors, and Windows is not such OS.

  11. Hi Mesta,

    Thanks so much for your information. I am new to Modbus, and have been read myself like one week about it.
    I am working one one project which needs to realise the Modbus RTU master function in C#, in order to read the data value from the slaves. I found that your library is the best, but ..my problem is that: Can you explain to me the structure of your library? In fact I do not know which parts are the library excatly. It has so 6 projects when I open it in Visual C# 2010… some other I can not even open…
    Thanks a lot. Hope you understand what I mean!

    BR
    Emma

    • Open MySample project, uncomment the sample that you want to execute and run it. It should work and get you started.

  12. Sorry mesta,

    I still did not figure out how to add your library to my C# project. Is that I add all the projects to my solution, then I can use the library? When I done like this, it still does not work. Is that MySample is a sample folder only to show how to programming with Modbus? MySample is not a library? Sorry for my questions, I really could not make it work!

    BR
    Emma

    • If your problem is to add an external library to your C# project you should:
      1- Create new project
      2- In solution explorer right click on solution and “Add” -> “Existing project”
      3- After adding the modbus library go under your project, right click on “References”, “Add Reference”.
      4- In the left tab, under solution, you will find NModbus project, so add it.
      5- You can now use the library.

      Here the msdn link: http://msdn.microsoft.com/en-us/library/7314433t(v=vs.80).aspx

      • Thanks so much mesta,

        It turned out that my “target frameWork” is not fit for this library. I have it .Net 4 client, and it should be .Net 4….
        Now I can use it 🙂

        BR
        Emma

  13. Hi mesta,

    Sorry for bothering you again. I would like to ask that, I want to make one software application which will read and display the Modbus RTU communication register values. How can I do it? should I create a IModbusSerialMaster first, then send message to slave? I want to display all the regoister values when I connect my software and PLC. Which is the function to read from RTU slave? Thanks a lot. Please even give me a general hint is also very appreciated. As I am new to this field, but need to get the work done still.Thanks!

    BR
    Emma

    • You should take the example of RTU communication and try to connect to the plc or the Modbus RTU simulator.
      Once you can read or write a register you can make a thread that keeps reading the registers from the plc.
      Something like this: https://www.mesta-automation.com/writing-your-first-hmi-project-in-c-wpf/

      • Hi mesta,

        thanks for answering . but they are too much for me I do not understand what do you mean. Can you explain little bit in detail? In fact what I want is: user enter slave ID, comport number, and baudrate then I have one button which will connect to the corresponding port automatically. Then the value of the registers should be displayed in datagrdiview…I get got stuck in this connect button….You gave is a very good library, but I do not know where should I start to do. Hope you understand, Also you know any Modbus RTU slave simulator?

        Thanks !

        • If you have problems with the connection of your device, you should ask help to the device’s manifacturer. Using NModbus implies that you know what is modbus and that you can debug the connection, and also you should have all the hardware needed for the communication.
          As you can imagine, i don’t know/can’t test your hardware, so this part is up to you.

  14. hello everybody , i have just download the NModBus library to read some Holding Registers of a device , in my c# 2010 express solution explorer added the reference to the modbus.dll from binary/net of the extracted folder , added all namespaces from modbus ie using modbus.data , using modbus.io and so on . then also added ftdAdapter.dll and wrote a small code to read holding registers using modbus RTU as explained by mesta at this page . But my project is not able to build .
    it says namespace name ‘Modbus’ could not be found (are you missing a using directive or an assembly reference? u guys are way ahead this issue , please drop me a line of advice .
    Thanks

  15. Hi Mesta I managed to get it right , actually I did not know before that u can add many projects under one solution , I have just had added DLLs before . when project of different .Net framework are added in one project , each individual project needs to be pointed to the frame work it was created on through the property of that project and then one project is required to be set as the start up project . This is the trick I was missing .
    Thanks for ur help !!

  16. Got out of obstacle but stuck at the next . well , I have a Modbus tester from namely “Modbus tester ” http://modbus.pl , this is something I have used for years . I have made some usual settings inside this software (protocol = Modbus RTU , pairity = even as per my device and so on) . starting address address = 3901 , no of registers = 2 , type of reg = holding and so on . This Modbus tester software reads my device correctly and also sets the display correctly in binary / hex / float etc . This is perfect . but when I run the same settings using same converter same device with Modbus RTU holding register read (start address = ushort 3901 and no of reg = ushort 2 , device address = 1) , my c# code throws an exception saying “Function code 131 , exception code 2 , the data address received in query is not an allowable address ” .
    For the time being this is beyond me , how come NModbus driver is interpreting the same working address as wrong ? anybody has any clue ? Please drop me a line .

  17. Hi Mesta,
    I have been in one problem for weeks, and can not get it work.
    My program works well with ReadHoldingRegister and ReadInputs, but not with the rest: ReadCoil and ReadInputsRegister. it always gives some error says: the combination of reference number and transfer length is invalid. Even I tried with only 1 register. It still gave the same error. You have any idea? Thanks so much. this is the last part of my app, I really want to figure it out…thanks

    • The only way to solve those errors is to check what packets you receive by using a Sniffer.
      Depending on the Modbus, you can sniff the packets with Wireshark if is Modbus TCP, or with SerialPortMonitor if is Modbus RTU (check the download links in the article).
      Then you can check the unit’s reply and understand what’s happening.
      The modbus protocol is quite simple and you will be able to decode it in not much time.

      • Mesta u r very correct . memory I was reading were meant to be read as a block but I was trying to read only 4 locations from top out of 20 , which was giving me a CRC error . Next , a location named 3901 in the manual = address 3900 in the c# code . I was able to fix the problem by looking at the response in the serial port monitor software . Then I hooked my Oscilloscope in Rtx of com port , that too was helpful . now NModBus C# API is ROCKING in my shop floor , thanks a lot for ur expert advice .

      • Hi Mesta,

        thanks for replying. It turned out my PLC is configured with those addreses.
        I want to ask another thing, how can I get the port disconnected? I have 2 buttons, one for connect one for disconnect..In connect click function, I create port and let it connect, but I can not get it disconnected…can you tell me how this could be done? Thanks so much!!

        • port.close(); closes the port and disposes the memory resources.There is no PING command for COM port , best way to check connection is that u write some known value to some location and when ever u need to test connectivity , u read the same location and then check for the content u received .

        • Thanks sachin singh,
          My problem still did not get solved yet.
          In my disconnect button click, I did it like this:

          port.Close();
          ConnectBu.Enabled = true;
          Dispose();

          But the result is the whole application exits. What I want is I can connect and disconnect manually, not exits. Is there anything related to the Modbus 485 cable I amusing now? Please help, so long time suffering from this problem. Thanks so much!

  18. Dispose(); is related to the port or to the application ? because it should be "port.Dispose()";
    But also i think that Dispose it’s not needed, port.Close() it’s enough.

    • Thanks mesta,

      I do not know why I use port.close(), it does not work. I do not know what is wrong. When I press disconnect button, then later press connect again it says: can not access port and it points to port.open() with this error.

      Also I want to display the connection status in the StatusStrip …it does not work as well…
      Thanks for helping.

      BR

  19. How i can read and write only one bit of a register with this library?

    I have the register Modbus RTU and the description of bits….

    Use a conversor Rs-232 (added USB) to Rs-485

  20. Esteban Brenes

    Hi, Im trying to use a PLC TWDLCDE40DRF, I just want to write to the %I0.0 input, Im using the following code

    using (TcpClient client = new TcpClient(“192.168.3.152”, 502))
    {
    ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
    ushort registerAddress = 0;
    master.WriteSingleRegister(registerAddress, 1);
    }

    but im getting this error:

    Modbus.SlaveException was unhandled
    Message=Exception of type ‘Modbus.SlaveException’ was thrown.
    Function Code: 134
    Exception Code: 2 – The data address received in the query is not an allowable address for the server (or slave). More specifically, the combination of reference number and transfer length is invalid. For a controller with 100 registers, the PDU addresses the first register as 0, and the last one as 99. If a request is submitted with a starting register address of 96 and a quantity of registers of 4, then this request will successfully operate (address-wise at least) on registers 96, 97, 98, 99. If a request is submitted with a starting register address of 96 and a quantity of registers of 5, then this request will fail with Exception Code 0x02 “Illegal Data Address” since it attempts to operate on registers 96, 97, 98, 99 and 100, and there is no register with address 100.

    I suppose the address is not 0, but I dont have idea what is the correct address.

    Thanks

    • To transfer 1 bit you should use WriteMultipleCoils, not WriteRegister. WriteRegister is only for integers.
      You can also use the Modbus library in c# in the end of the article to make tests with your plc.

  21. Hi Mesta i have had started long time ago from here now i have written my own modbus implementation for S7 300 / 400 / 1200 and also have written a small library using tcp ip fetch and write service to talk to above mentioned PLCs and they all work as expected . There is one thing i am still strugling with and that is drawing line circles and rectangles on the winform . While developing a SCADA one has to show pipelines and stuff , is there any windows OS paint like program using which i could draw those static graphics on winform ?

    • In windows forms you can just use bitmaps and make them visible/invisible depending on the state of some variables.
      That’s what Scada designers do by the way.

  22. Hi Esteban Brenes I recommend you use wireshark to troubleshoot anything on your tcp port . Very important to judge the location of the problem , in your software / connecting media ( cable switch ) or in the PLC device itself.
    Hey bingshanxuelian . You problem not solved yet ? Give me you email address i shall snd you one c# class which works fine for me .

  23. Hello everybody,

    I am using this great library in TCP mode with a PC. The PC could behave either as a master or as a slave. It works fine in both modes, marter and slave. When the PC behaves as a slave gets is own slave address in the constructor:

    ModbusSlave slave = ModbusTcpSlave.CreateTcp(slaveId, slaveTcpListener);

    With this method, the simulated slave address of the PC server is ‘slaveId’.

    However, my PC answers to all masters requests independent the value of UnitID present in the TCP frame sent by the master. I have been looking to some management of the requests addressed to a particular slave like this one for the ModbusSerialSlave:

    // only service requests addressed to this particular slave
    if (request.SlaveAddress != UnitId)
    {
    _logger.DebugFormat(“NModbus Slave {0} ignoring request…”, UnitId, request.SlaveAddress);
    continue;
    }

    But I haven’t find any place where the management of InitID is done in the ModbusTcpSlave class.
    Could any one help me where to find how to block server responses indepent of its UnitID?

    Any help is wellcome!

    Thanks!!

    • I know that probably it’s not the answer that you expect, but you should ask this question in the nMdobus google group: https://groups.google.com/forum/#!forum/NModbus-discuss
      To give you an answer i would really need to dig inside the sources and check wether the message get decomposed and what they do with every piece of the frame.

      • Thank You.So far i have been drawing some line horizontal and vertical using label and putting many minus sign – or vertical pipes | and also for arrows which is ok but people these days expect heavy graphics even on PCs controlling machines . This is crazy …

    • Hii i saw a unit id in protocol but here in sample code given above it is not mentioned

  24. Dear Eloy, writing your own modbud tcp query is not complected at all . you may very easily study the modbus tcp protocol and send a message frame using c# raw tcp connection , and the device would respond to it. Me too started out with this library but started to write my own message frames and it works quite well. Also learn little bit about Wireshark which may be of great help finding out problem in your code initially .

  25. Hi Mesta, sorry for digging up this old post, but i would really appreciate your help.

    I have Visual Studios 2013 and i downloaded the NModbus Library from the Google-Group.

    I opened MySample.csproj but i can’t build or exectue “Driver.cs” because of 2 Errors.

    1)Modbus.IO.StreamResource is defined in a not referenced Assembly…
    2) Metadata “FtdAdapter.dee was not found in /source/src/FtdAdapter/bin/Debug

    What did i do wrong, and how can i fix it?
    Please help
    thank you

    • I downloaded it right now and compiled with Visual Studio 2013 without any problem. Did you unzip everything in the folder that you downloaded or only “src” folder? Maybe that’s the problem. Also remove the incompatible projects in the solution.

  26. hi Mesta, thank you for your quick reply!
    I unziped everything.
    I got a couple folders like
    -bin
    -source
    and a couple files like
    NModbus_net-3.5.chm

    >in source i got folders and files again.
    >i open src > MySample > MySample.csproj but i can’t build Driver.cs nor run any .cs files…
    I deleted the incompatible projects already, but it didn’t fix the problem 🙁
    When i want to start “driver.cs” i get the message:”A Project with the Returntyp “Classlibery” can’t be run…” (rough translation).

  27. Update, i could build the “MySample” now (i just copied the files into the “Project” folder again and deleted the old files…
    But i still can’t run driver.cs
    I still get the message about the class libery…
    Thank you very much for your help

  28. I got it now, there was a fault setting, that i didn’t run the selected cs but always a default cs…
    thank you though!

  29. hi
    i want to help . i am able to read 16bit data from PLC like 4digit number but when it comes to 32bit, big number like 9digit , i am not able to read from register. can you help in this regard. i am communicating PLC through .Net program. Do you have any example which can read a 32bit value from PLC.
    thanks
    santosh

    • It depends if the PLC supports 32bit transfer with Modbus. For sure you need to read 2 consecutive registers, then you need to convert the 2 numbers to Hexadecimal, then depending if it’s floating point, integer or what else, you need to convert from hex to your unit.
      Just google how to do the conversion from hex to float / int and you’ll get what you are looking for.

  30. Hi Mesta
    I designing HMI software. My PC has 4 comport. I need access data from 4 PLC. Could you hepl me How to creat multi thread for multi comport?

  31. Hello,
    I just downloaded Nmodbus source and binaries. When I am running example code ‘Driver.cs’ given in Nmodbus source , i am getting IOException Checksum Failed to match .
    I am running code as-is without any alteration.
    How do I debug and where do I find Nmodbus Functions and Exceptions documentation?

  32. anybody has a working solution for visual c# 2010 Express? I can not convert the files.
    I would actualy like to have the modbustcp_master example but can’t find it and can’t convert
    Thanks

  33. I have been working with this library for almost a year and have a problem that I can’t solve. In searching through the NModbus discussion groups, it looks like other people have this problem as well and it hasn’t been resolved, (see https://groups.google.com/forum/#!searchin/NModbus-discuss/close$20client$20port/nmodbus-discuss/QMSyOfRcIrU/rxpCdroOxNMJ and https://groups.google.com/forum/#!searchin/NModbus-discuss/close$20client$20port/nmodbus-discuss/OhvR3hLOD8w/ncBdaQ1PUKAJ).. The problem is related to shutting down the TCP ports when the ModbusTcpSlave is disposed. If I dispose of the slave, the ports are still active. If I iterate through the Masters collection and manually close the clients, then an exception is thrown (either IO Exception or Object Disposed Exception) that I haven’t been able to catch, so the software simply crashes. This seems like a bug within the class library since the software is still trying to communicate on the port after the clients have been closed and the ModbusTcpSlave has been disposed. The only way I’ve found to close these ports is to kill the software altogether and start over. Is there a recommended way to close the client ports?

    This is a real problem that may require my client to walk away from the software altogether. Any help would be appreciated.
    Thanks,
    Joe

    • This seems more a socket related problem, rather than a nmodbus library problem.
      You should check if the ports are open and in what state, if they are in listening state or in wait state.
      Searching around I found this thread: http://stackoverflow.com/questions/425235/how-to-properly-and-completely-close-reset-a-tcpclient-connection
      He suggests to close the stream before closing the socket.
      Also you can enable network tracing in visual studio: https://msdn.microsoft.com/en-us/library/a6sbz1dx(v=VS.100).aspx

      • Thanks for your quick reply; however, properly closing the ports is not the problem. The problem is that as soon as they are closed, an ObjectDisposedException is thrown from NModbus.

        In reviewing the NModbus source code, this is what I think the problem is: in class ModbusTcpSlave, in the method AcceptCompleted, a new master is created when a client connects and a corresponding event handler is added for masterConnection.ModbusMasterTcpConnectionClosed. The method linked to this event handler is supposed to remove the master and close the socket, but it is not being called. So, if I call the Dispose() method on ModbusTcpSlave, the slave is shutdown, but the master ports remain open. I verified this using NETSTAT from a command line. If I manually close the masters, they are closed, but the event handler created when the connection was first made is still active and polling, so the software immediately throws the exception and kills my software.

        This is a NModbus problem because only NModbus can unsuscribe from the event handler. I have no way to control this event handler from my code. I have tried to catch this exception, but haven’t been successful.

        This is a problem in my software because if the ModbusTcpSlave needs to be shut down and restarted (e.g., in the case of a communication failure), then when it is restarted and the master reconnects, then the original ports remain open. Eventually, those open (but now dead) ports are causing the software to crash.

        I think a simple solution would be to unsubscribe from the masterConnection.ModbusMasterTcpConnectionClosed event in the ModbusTcpSlave.Dispose() method. However, I would really like your opinion on this matter, especially if there is a way to properly dispose of the slave and master connections.

        Thanks,
        Joe

  34. Hello Mesta,

    Great blog I have just one question. In nmodbus can we somehow read structure of query message which send master to slave?

  35. Hi Mesta,

    I have connected four different slave ids. I am communicate to them using loop and timer. I am able to read the data from controller but while writing the data using write function, facing CRC error.
    Can you please help me in this?
    I have referred following article..

    http://www.codeproject.com/Articles/20929/Simple-Modbus-Protocol-in-C-NET

    Write issue is inconsistent….

    • Usually for Modbus communication I use NModbus. It’s possible to debug the error and check what’s wrong with your library, but if I would be in your place, I would switch to NModbus because of better documentation, bigger user base and the certainty that it just works. If you go on with your library, you’re on your own with bug fixing.

      • Hi Mesta,
        I am trying to read data from following config

        byte slaveId = 3;
        ushort startAddress = 0;
        ushort numRegisters = 36;

        With master.ReadHoldingRegisters i am getting time out exception.

        i have set the read and write timeout to 1000 (1 second)

        can you please help..?

        • You need to use a serial port sniffer to debug modbus problems. There is a link in the article, download it then sniff the packets that you are sending with the new software, you also sniff the packets that you sent with the old software that worked, check the frames and understand what’s different, then adjust the new software.

        • Hi mesta,
          Its working…
          Now no issue while reading and writing register in loop ..
          Thank you !!!

  36. Great blog, consider updating link to the new libs at https://github.com/nmodbus4/nmodbus4

  37. Hi, How I could use this code for a .Net program?. I have to communicate a PLC with a PC using Modbus RTU and I have connected PLC with a PC using a RS485-RS232-USB converter. How I could read and write memory registers from the PLC with this address:

    Data Registers D0000-D4095 (as you see in the PLC) = 450001 – 454096 (Modbus address)

    Thanks!

  38. Hi, I have same problem. This my code (i usу nModbus4):

    SerialPort port = new SerialPort(“COM3”);

    port.BaudRate = 115200;
    port.DataBits = 8;
    port.Parity = Parity.Even;
    port.StopBits = StopBits.One;
    port.Open();

    IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

    byte slaveId = 62;
    ushort startAddress = 2;
    ushort numRegisters = 20;

    ushort[] registers = master.ReadInputRegisters(slaveId, startAddress, numRegisters);

    I am getting IOException Checksum Failed to match 62,4,0 != 62,4,0,0,2

    My device work with diferent PLS (RS-485/ModbusRtu) like Honeywell ML200 and i have not problem.

    But here … 🙁

    Please help!

    • Hello, you can use FreeSerialPortMonitor to understand what’s going on. You have to debug the communication, understand what is the request from the PC and what is the reply from the device. Then you connect a working device and you check again what is the request from the working device and what is the reply.
      It’s probably that the function is not supported by the device, or the configuration is not correct.

      • Hi, Mesta.
        I use DAQFactory Monitor:

        Tx (10:02:57.706): \062\003\000\002\000\020\225\010
        Rx (10:02:57.710): \062\003\000\000\000\000\000\000\000\020\230\003\082\000\010\003\082\005\070\007\058\009\046\011\034\013\022\015\010\016\254\018\242\020\230\028\038\036\012\043\166\051\179\221\053

        When i use nModbus4 :

        Modbus.IO.ModbusSerialTransport Write – TX: 62,3,0,3,2,0,20,255,10

        Modbus.IO.ModbusSerialTransport ReadResponse – RX:62,3,0,0,0 – and that’s all.

        I am get only 5 registers.

        When i go to “Modbus.cs” and change “public const int MinimumFrameSize = more than 6;” i get new message “Message frame must contain at least (6) bytes of data”.

        Where is the problem?

      • I used all old sources.

        • I can’t understand how with that function you obtain those values. I used your code and I got the expected message.
          The request frame is “Node” / “Address” / Start Address #1 / Start address #2 / N° of registers #1 / N° of registers #2 /
          And you have not six, but seven bytes. Also you are getting function code 3, that it’s “Read holding registers” but you actually wrote ReadInputRegisters. And infact in the first post you obtained a 62,4,0, that it’s the correct number of the function. Now if you are trying to read holding registers with the function that read inputs, you obviously can’t.
          What you have to do is to go step by step in the sources and understand what’s going on when you create the frame. Also if you modified the sources, or you have a suspect that they can be modified, I suggest you to go back to the original version.
          If you need some modbus documentation, you can go here:http://www.simplymodbus.ca/FC03.htm

    • I experienced a similar issue today like in the above comment:
      “I am getting IOException Checksum Failed to match 62,4,0 != 62,4,0,0,2”

      I receive a “valid modbus response” with slave-adress, functional-code, correct number of following registers, the registers contain the values I expect and the crc-checksum is correct. (Even calculated it on my own with the Utlity provided by NModbus4)
      But *somewhere inside the library* (i assume “ModbusMessageImpl”-class), a few bytes of the response get dropped / get lost. And therefore, such exceptions arise. After some hours I was not able to locate the cause for this. In my opinion, the response is valid, but NModbus4-lib is doing something wrong!

      Sadly, noone is reacting to such issues, see for example here: https://groups.google.com/forum/#!searchin/nmodbus-discuss/checksum%7Csort:relevance/nmodbus-discuss/suNBAIK0quE/PYSZujzwm7EJ (This question is from someone else, not me)

  39. Great article. I try to connect my Laptop to a Schneider Stepper Motor(LMDCE853) with ModBusTCP, connection is OK. Reading the address with single byte also fine. However, the error popup when I try to read the address with 2 or 4 bytes number( start address and read the length of data as 2 or 4) .

    What’s the problem?

  40. Hi, I am using the library in ASCII Mode.

    Is a function implemented to convert the recieved words like decimal 48 to a 0 in string- or hex-format in ASCII?
    Or do if have to implement myself with a case structure?

    Thanks for your great work 😀

  41. Hello,
    I’m new to C#, so sorry, if thats is the reason something wrong.
    I look through those examples, and i somehow cant (understand/get to work) that slave read. I’m trying to write winforms app, that works on data change. If i’m correct, then for that answers ModbusTcpSlave right?
    So i copied your source code, tried to run it…and exception.
    “System.ArgumentException was unhandled
    Message: An unhandled exception of type ‘System.ArgumentException’ occurred in System.dll
    Additional information: The IAsyncResult object was not returned from the corresponding asynchronous method on this class.”

    And code is

    private void simpleButton2_Click(object sender, EventArgs e)
            {
                byte slaveId = 1;
                int port = 502;
    //            IPAddress address = new IPAddress(new byte[] { 192, 168, 161, 129 });
                IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });
                // create and start the TCP slave
                TcpListener slaveTcpListener = new TcpListener(address, port);
                slaveTcpListener.Start();
                ModbusSlave slave = ModbusTcpSlave.CreateTcp(slaveId, slaveTcpListener);
                Thread slaveThread = new Thread(slave.Listen);
                slaveThread.Start();
    
                // create the master
                TcpClient masterTcpClient = new TcpClient(address.ToString(), port);
                ModbusIpMaster master = ModbusIpMaster.CreateIp(masterTcpClient);
    
                ushort numInputs = 5;
                ushort startAddress = 10;
    
                // read five register values
                ushort[] inputs = master.ReadHoldingRegisters(startAddress, numInputs);
    
                List items = new List();
                for (int i = 0; i &lt; numInputs; i++)
                {
                    items.Add(&quot;Input &quot; + (startAddress + i) + &quot; &quot; + (inputs[i]));
                }
                memoEdit1.Lines = items.ToArray();
                
                // clean up
                masterTcpClient.Close();
                slaveTcpListener.Stop();
                
    
            }
    

    I'm using that modbus simulator.
    I hope you can help somehow. Thx in advance.

    • You can use the modbus tcp client that I posted in the section “Other Modbus TCP libraries”, to check if you configured correctly the simulator. Then if you can connect with that application, you can probably connect also with NModbus.

  42. Hi,

    I made a Windows Form to communicate via nmodbus with a slave. (ASCII Mode).
    Reading works fine and I can store the Registervalues in an Array and print them in Labels. Now I want to write a Register. And the slave will send a respond message (Ok or failed).
    With the terminal programm of the sample it works well. (I think ReadRequestResponse in ModbusAsciiTransport is writing it to a byte[] called frame). I want to use the responded message from the slave in a Label. So I can see in Form1 if I the slave accepted the changes or not. How can I implement this?

    thanks for the Support here

    • ASCII Modbus is limited, only the master can start the communication and the slave responds only when it’s interrogated by the master.
      What you can do is probably to store the result in a register, let’s say 0 = not done, 1 = Ok, -1 = Failed, then read the register that contains the result, and reset it before starting another write operation.

      • Ok but it is responding. Maybe it is not really ASCII. Because when I use “mysample” I can see the TX 58, 48 … (So it is ASCII) and then RX 1, 16, 0 … (So it is RTU?). But the Problem is that I have my own class “communication” and my own form1 and I can not Access the data from Modbus.IO.ModbusAsciiTransport ReadRequestResponse because it says it is inaccessible due to its protection Level.

  43. When master makes a write, the slave respond with the same query that the master wrote, so the master can verify that the instruction has been sent and processed correctly (http://www.simplymodbus.ca/FC06.htm). So there is no need for you to check ReadRequestResponse, becuase it’s used only to validate the communication.

    • Thank you Mesta, I know that the normal Response is the same query that the master wrote. But if the writing fails it responds with another message. So it would be nice to read the message. But I if it is not usual to read the Response I don´t need to read it.
      My Problem is that after sending the write request I want to close the port again. But the program throws me because the Serialport is busy. I thought the best would be to read the responding message and then close the port. But it would be possible just to wait some time till it is not busy anymore and then close it. (Maybe with a timer)
      What is the best way to deal with this problem? I think everybody who works with Modbus has to solve this… So there should be a common way to do it.
      Thank you so much for responding so fast and for all the help

      • I realized that the Problem is in the writing command already. The Problem is not closing the port. So a delay or reading the response does not help. But I still don´t know what to do against the modbus.SlaveException in line 161 of ModbusTransport.cs.

  44. Hi,
    As i can see all the example above uses Ushort as address type, that means maximum register address is 65535, but if i want to access register address beyond this like say 400001 (which is beyond ushort range) how can i achive it. I am new to NModbus, Please guide me through.

    Regards
    Harsha

  45. friends … I need a program that manages the reading done on a Modbus xml Anyone know how to thank you … this example does this ?

  46. Hello, I want to connect PC usb-rs485 breakout board with stepper motor controller (DS5073A), it dont have to be in real time. I made your example and with simulator everything work great, but when i try to connect to hardware I get no response. Do i need some additional changes to use rs-485?

  47. Hello everyone,

    I use two differents Modbus TCP library for slave server.
    Each library use TcpListener.

    I have a problem with both.

    When my client is disconnected :
    Hide Copy Code

    CLIENT SERVER
    FIN, ACK —->

    (http://uploads.im/omOLI.png)

    Result, just the first connection after the start of server is done.

    Please, do you have any idea ?

    (PS. no problem with other Modbus library and server in Java)

    Thanks !
    Aurélien
    from France

    • Hello Aurelien, there is a bug with the disconnection and reconnection from a server. You can read through the comments to check if it’s your case. There is a new library, NModbus4, or you can get the old code from here:https://github.com/mesta1/nmodbus
      I just reverted some commits that introduced the bug.
      Hope it solves.

  48. Joseph Nones

    Hello Mesta,

    I have read forums entries here from 3 years ago..and i dont seem to find a solution for my problem. ANd so im entering into the loop.
    I am into automation project right now. Need to control a despatche oven machine. Its controller based system that applies a MOdbus protocol. Last week I downloaded the Nmodbus project. I had it working (perfectly) but only with PLC modbus simulator as my slave. My boss was glad to hear that i have control now with the machine. ..But, it wasnt the case when i connected with the real machine. I set and followed all the configuration settings if the serial port. But when the code run into these line
    var values = master.ReadHoldingRegisters(slaveId, startAddress, 1);
    textBox3.Text = values[0].ToString();
    ..the program got in to “stalled” status . I had to close it down on the task manager..

    Additional info: There is a third party software running in the master pc that seems to have no problem using the modbus. It can actuaLLY read out data from the machine. And I think to rule out some probelem in the machine itself..

    Hope to hear from you…and to anybody who reads this 🙂

    Thanks, Joseph

    • If you are using serial ports it means that there can be only 1 master / client, and as many slave / server as you want. Your program is a master, same as the third party software, so they can’t live both in the same Modbus network.
      There are several solutions to these issues, that can be by adding hardware / software, depending on the plc that you are using.
      However if you have to test this, I would suggest you to shutdown the master pc and connect with your laptop to check if it’s working.

      • I only closed down the third party software and closed all processes handling on serial port(com1). It doesn’t seem to work. It just timed out if I set read time out value on my port. But I ve come across another solution..The Data Terminal Ready property..I don’t know if it will work or not..but ill give it a try..I’ll also try using a laptop..Ill let you know..

        • If the HMI works and your software doesn’t work, there is something wrong in the configuration. If you have access to the remote pc, just install a serial port sniffer, capture the packages and check what’s wrong with your packages. If you scroll through previous comments, you’ll find more of these issues.

        • Man you’re fast! I was expecting ur reply tomorrow. I was only given until tomorrow to figure out the Modbus communication..so i must be able to connect it.
          The controller is a Protocol3 . It supports Modbus RTU. Currently there is software running at configuration 9600,None,8 bits, 1 of the serial port. There is no problem at all, only the software is limited in functions. So we have to design a system that can automate the machine based on the company’s data architecture. Meaning it has to be connected with our manufacturing system where we can automate and control. Because right now we have to depend on the operator (human) which has been proven to be a source of lots of problems in the production floor…And i just couldn’t even connect. 🙁
          The machine has no HMI, but it has a small LCD display with a small panel to make the settings. The third party software serves as the HMI .. let u know tomorrow

        • Well that’s a bit different to what I expected. Did you read very carefully their manual ? http://www.despatch.com/pdfs/manuals/Modbus_e102.pdf

        • I got it working! Apparently there was another process taking on hold of the serial port. I used the process explorer app. Then I discovered another exe file using the device\com1..:)

  49. Hi mesta
    Im working on Modbus ASCII mode, I want to read and write to the master plc from my Windows form.

    • I’m getting Checksum failed error.
      And thanks for your great work.

      • Hello, I hope that you already solved. In any case checksum failed means that you are reading wrong registers or wrong data. Just search through comments for checksum failed, you will find some tips.

        • I got the CRC checksum error before..when i tried writing to a “read only” register. You may check first if the register you are trying to acccess is a R or R/W

        • Thanks for your quick reply
          I am able to read the register value using “Modbus slave” software. But I couldn’t get those values in my program. Getting Checksum error. I used the same slave address, baud rate, data bits and parity.

          Please tell me which function I have to call for the following scenario.
          My PLC is master and my PC is slave. Conected using RS485 to USB.
          But,
          StartModbusAsciiSlave(); function isn’t defined.

          Whether I have to call StartModbusSerialAsciiSlave() or StartModbusAsciiSlave()

          Please share if any tutorial for modbus ASCII mode.

  50. Hi Mesta,
    Im working on Modbus ASCII mode, I want to read and write to the master plc from my Windows by protocol Modbus TCP/IP (read input and write variable ) .

    • That’s great! Read the articles, watch the video, practise with the simulator, then learn how to configure your plc and you’ll be done 🙂

      • my PLC the rokwell micro 850 conected with my PC by a local network .
        so now i can read input the PLC by protocl TCP/IP very good 🙂 .
        i need to write in input and variable by modbus TCP/IP .
        thanks for your great work.

  51. Hey Guys
    I have my own written MODBUS RTU drivers in C#. You may get the full source code with. See demo at
    https://www.youtube.com/watch?v=RyHeiDeG3IA&list=PLKeKQZBhrPfE8KpsZqS5EZSdUIQ_Tx6rt&index=17
    I am in the process of developing my own PLC too.
    Thank You

  52. hi Mesta can u help me to create a simple ide to read and writ coil in visual studio using windows form

    • If you don’t know where to start, have you considered using AdvancedHmi ? It comes with its own modbus driver and you can get things done quickly and it’s also based on Windows Forms.
      Once you are more familiar with it, you can switch to the NModbus protocol.
      In the future I’ll make some sample applications for the various drivers, but it will take time.

  53. Hi everybody
    I use Delta DVP series plcs which have internal relays called ‘M’ so Have you got any info how to read ‘M’ relays besides registers

  54. Hi Guys, Please guide me to solve the below problem. Application will support Telnet Server? There is no seperate server (It is a device with IP). How to read holding register from Telnet server i.e Device with IP (3 One Data)

    • My Application connected successfully with Telnet Server using TCPClient. But while ReadingHoldingRegister from Telnet server I am getting following Error’s in different scenario.

      1. An existing connection was forcibly closed by the remote host
      2. The requested address is not valid in its context
      3. Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
      4. The operation is not allowed on non-connected sockets.

      Note: Telnet Server is a device not a server i.e We can’t run TCP listener

      R Muruganandhan

      • using (TcpClient tcpClient = new TcpClient())
        {
            tcpClient.Client.Connect(ipAddress, tcpPort);
            tcpClient.LingerState.Enabled = true;
            tcpClient.LingerState.LingerTime = 50;
            tcpClient.NoDelay = true;
                           
            //Modbus IP 
            using (ModbusIpMaster master = ModbusIpMaster.CreateIp(tcpClient))
            {
                master.Transport.Retries = 2;
                master.Transport.ReadTimeout = 600000;
                master.Transport.WriteTimeout = 600000;
                //Read Holding Register
                //40159 as 159
                master.ReadHoldingRegisters(159,6);
            }
        }
        
        public ushort[] ReadHoldingRegisters(ushort startAddress, ushort numberOfPoints)
        {
             //Slave Address 0101
             return base.ReadHoldingRegisters(0101,startAddress, numberOfPoints);
        }
        

        Above coding is used in my App and not working for me. (Note: Above 3 posts or reply by me)

        • Did you try to just run the sample code, instead of your version?
          You use tcpClient.Client.Connect(ipAddress, tcpPort); but the TcpClient Connection/Disconnection are handled directly from NModbus.
          Still, this is a guess. as the informations on the error are limited and I have no access to the hardware.

        • Did you try to just run the sample code, instead of your version?
          Yes. Same issue occur

          TcpClient Connection/Disconnection are handled directly from NModbus
          ——————————————————————————————-

          Used SerialPort to read holding register, but we need result using TCPClient

          using (SerialPort port = new SerialPort(“COM1”))
          {
          // configure serial port
          port.BaudRate = 9600;
          port.DataBits = 8;
          port.Parity = Parity.None;
          port.StopBits = StopBits.One;
          port.Open();

          // create modbus master
          IModbusSerialMaster master = ModbusSerialMaster.CreateAscii(port);

          byte slaveId = 111;
          ushort startAddress = 159;
          ushort numRegisters = 5;

          // read five registers
          ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);

          for (int i = 0; i < numRegisters; i++)
          Console.WriteLine("Register {0}={1}", startAddress + i, registers[i]);
          }

        • Mesta,

          Before reading Holding Register, what are the steps to complete i.e We need to write in register before reading? Can you explain Step by Step procedure or recommended link to go through.

          Thanks and regards,

          R Muruganandhan

        • Hi, your hardware needs to be configured for Modbus communication.
          Once it’s configured, you can use NModubs or other libraries and tools to setup the connection.
          In the article I talk about these tools.
          You can also contact the hardware manufacturer to get user manuals, specs and more details about the communication.

        • Mesta, We are using ModScan64.exe (Wintech). It’s working fine in our environment (i.e. using our IP and Port number).
          It is 3 rd party software and we are facing some data issue while using that software. This software reading Holding register data accurately except one value. So as my analyze hardware already configured with Modbus communication. Please guide me if I am wrong.

          Link For Reference: http://www.win-tech.com/html/demos.htm

        • Good, use wire shark, sniff the packets and compare them with nmodbus packets to see what’s wrong.

        • Mesta,

          Last 2 days, we analyzed the packet using wire-shark but we unable to point out the issue. What is Sniff the packet? Please guide me where we are missing.

          Thanks in advance.

        • If the two packets are exactly the same, I would expect that the controller responds in the same way. If they are not the same, you have to determine from the packet if the function is the same, if the node is the same and if the registers are the same. This requires some knowledge about Modbus protocol, nothing difficult anyway. In the article there is a link on the documentation.

      • Mesta,

        The above articles talking about Serial Port or TcpClient 127.0.0.1 , 520 but my requirement is

        using (TcpClient tcpClient = new TcpClient())
        tcpClient.Connect(10.100.XX.XX, 30000);
        ModbusIpMaster master = ModbusIpMaster.CreateIp(tcpClient)

        I tried to connect using above IP and Port. Its connected but I am not able to read Holding Register data (master.ReadHoldingRegisters())

        Thanks and regards

        R Muruganandhan

        • Mesta, One more doubt

          Before reading holding register data, we need to run TCP Listener? If Yes, then my next doubt is
          How to Run Listener in Telnet server which is Hardware device? Please help to solve this issue

        • TcpClient oTcpClient = new TcpClient();
          oTcpClient.Connect(“10.100.XX.XX”, 30000);
          oTcpClient.ReceiveTimeout = 60000;
          IModbusSerialMaster masterSerial = ModbusSerialMaster.CreateRtu(oTcpClient);
          byte slaveId = 100;
          ushort startAddressSerail = 150;
          ushort[] registers = masterSerial.ReadHoldingRegisters(slaveId, startAddressSerail, 10);

          Above code working for me. Thanks for your kindly help

          Thanks and regards,

          R Muruganandhan

  55. I am trying to run the simulator with serial ports. I have com 9 and 10 set up using the null-modem port emulator in my device manager but I cannot set the simulator for these coms. I stays on com 3 and I cant change it….any ideas?

    • There is a “settings” button that has the form of a COM port. It’s the forth on the top right, starting from the floppy disk button. That will permit you to configure the COM port.

  56. I am trying to read the holding registers(relay settings) from a GE relay. I am connecting but not seeing any of the values on the screen. Has anyone done this before. I am using ModbusSerialAsciiMasterReadRegisters(). Any help would be much appreciated.

    • Hi John, these problems are common problems that can debugged easily. The problems can be caused by wrong COM port settings, wrong node number, wrong register address, wrong functions. Plug a working Modbus program and a Serial port traffic analyzer. You can read previous comments to see how other people solved the same problems as yours.

  57. Hi Mesta .

    I am really thank for you sharing, it is working well. unfortunately I found a problem with Modbus RTU, when I read data holding register from address over 43000 (I know that those data is 32bits, while your library is ushort 16bits). Please help me to solve this problems, I am nearly complete my project.

    best regard.
    V_Sarak

    • You probably have to read two consecutive registers, then compose the 32 bit number by taking the register with the highest bits and shift it.
      Something like this:
      Value = highRegister << 16 + lowRegister

  58. unfortunately, I cannot post long code since the posts won’t show up then.

    I get this error:

    modbus unable to read data from the transport connected party did not properly respond

    However I can write to the external device (Eurotherm 3504 temperature controller).

    Do you have any ideas?

    Thanks!

  59. Dear Mesta,

    I think the problem is that I am using the wrong “UID”. In addition to the Register, I can set a UID in Ananans, which must be 2.

    How can I define the UID here in the nModbus TCP library? Thanks!

    By the way: Thanks for the great work here. I also love your examples!

    Michael

    • Hi Michael, you can use the UID when you read. Actually you are using this:
      master.ReadHoldingRegisters(startAddress, numInputs);

      but you should use this method:

      byte uid = 2;
      master.ReadHoldingRegisters(uid, startAddress, numInputs);

  60. Dear Mesta,

    you are awesome! Thank you so much ;-).

    If you’ll ever be in the area of Augsburg (Germany), I owe you a beer in a nice pub ;-).

    Michael

  61. Dear Mesta,

    I am trying to use Modbus to read data from an XGB Series PLC (from LSIS). I am not sure how and where can I make changes to this code in order to be able to use it. Can you please give me few inputs.

    Thanks Raju.

  62. Sample.cs needs some work as only example is for an inbuild slave on local host. and does NOT indicate the TCPClient needs to be opened in that example, but it still works, oddly enough!

  63. Hi there,

    Does nmodbus4 support actual Modbus TCP or is it Modbus RTU over TCP?

    I need Modbus TCP.

    Thanks

  64. Hi Mesta, I have CitectScada running in Windows XP connected to Modicon PLC. I’d like to make a C# App to read and wrtie to the CitectScada Tags but I found only one solution which is to make unmanaged dll c++ to connect both which is kind of tricky. Now I am thinking to use NModbus with C# and read\write in same computer with CitectScada I wonder id this is practical, thanks in advance

  65. For anyone who might be interested, there are Modbus Master and Modbus Slave Simulator apps based on nModbus library and coded in VB Net:

    https://www.advancedhmi.com/forum/index.php?topic=2567.0

    FREE Registration is required in order to download these and they are both intended as testing tools.

    MODRSsim2 simulator mentioned by Mesta might be a better choice of a Slave Simulator since it provides more features.

  66. hi
    can any one help me in connecting c# with delta modbus.

  67. I want to connect PLC DVP with RS232 port to C# windows form application
    would you please send me a library to communicate with inputs and outputs and the other registrations
    Or if there is another way to do this please tell me.

    I am grateful for your consideration and I am looking forward to hearing from you

    Sincerely yours,
    Sara

  68. Fairozkhan Inamdar

    Hi this is Fairozkhan,

    I am very new to ModBus Protocol. Please suggest me.

    We have a data center AC running two units both are interconnected with RS 485 and supports ModBus protocol.

    Now i want to shutdown the alarm on the second unit. But the interface is connected to first unit through RS 485.

    Please let me know how to send the modbus commands to these individual units

  69. Hello. Could you tell me about the NModbus4 library. I am trying to create a modbus slave rtu based on this library. Slave was created and it works 1 on 1 with the master. But if another slave appears, as I understand it, the library-based slave accepts responses from another slave into its receive buffer and sends an error – Unhandled exception of type “System.ArgumentOutOfRangeException” in Modbus.dll
    More information: Maximum amount of data 127 registers.
    Tell me how you can make the slave listen only to the parcels intended for him by id from the master?

    • Hello. Did you come any further? I am trying to make a Modbus RTU slave simulator as well. It should simulate at least two slaves simultaniously.

  70. Can anyone tell me how to use NMDBUS in single modbus tcp server in Multiple pages i C# visual studio??

Leave a Reply

Your email address will not be published.