Quickly deploy a Modbus TCP server using libmodbus

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Quickly deploy a Modbus TCP server using libmodbus

In modern industrial communication, Modbus protocol is widely used due to its simplicity and ease of implementation. This article will provide a detailed example on how to create a TCP based Modbus server using the libmodbus library. This server is capable of handling Modbus requests from clients and responding to these requests.

Complete code (Chinese comments):

1. Initialize Modbus TCP server

Firstly, we need to introduce the libmodbus library and initialize a Modbus TCP server. In our example, the server will be bound to a local address127.0.0.1and port1502. By calling themodbus_new_tcpfunction, we created a pointer to themodbus_tstructure, which will serve as the context for all subsequent operations:

ctx = modbus_new_tcp("127.0.0.1", 1502);

2. Mapping Modbus Data Model

Next, we need to define the Modbus data mapping that the server will use. This step is completed through themodbus_mapping_newfunction, which allocates and initializes memory for different types of Modbus data (bits, input bits, hold registers, and input registers):

mb_mapping = modbus_mapping_new(500, 500, 500, 500);
if (mb_mapping == NULL) {
    fprintf(stderr, "Failed to allocate the mapping: %sn", modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
}

3. Listen and accept client connections

Once the data mapping is ready, the server can start listening for connection requests from clients. Usemodbus_tcp_listenfunction to start listening, and then usemodbus_tcp_acceptto handle client connections:

s = modbus_tcp_listen(ctx, 1);
modbus_tcp_accept(ctx, &s);

4. Receive and respond to requests

The main loop of the server includes waiting for client requests, receiving requests, processing requests, and sending responses. This is achieved by continuously calling themodbus_receivefunction to receive requests and using themodbus_replyfunction to send responses:

for (;;) {
    rc = modbus_receive(ctx, query);
    if (rc > 0) {
        modbus_reply(ctx, query, rc, mb_mapping);
    } else if (rc == -1) {
        break;
    }
}

5. Cleaning and closing resources

Once the server completes its task (usually due to errors or client disconnection), it needs to release all allocated resources and gracefully close the connection:

printf("Quit the loop: %sn", modbus_strerror(errno));
if (s != -1) {
    close(s);
}
modbus_mapping_free(mb_mapping);
modbus_close(ctx);
modbus_free(ctx);

Through the above steps, we demonstrate how to create a fully functional Modbus TCP server using libmodbus. This server is capable of handling standard Modbus function codes, including operations for reading and writing single or multiple bits and registers. This example is not only applicable for educational and testing purposes, but can also serve as a foundation for practical applications.

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.