
Recall first from Modbus RTU and Modbus TCP
- RTU uses timed silence for frame boundaries and sends its CRC-16 low byte first.
- On a two-wire RS-485 bus, the transmitting device releases the bus after its final stop bit so the next device can transmit.
- The MBAP Length field counts the unit identifier and the PDU.
Connect to a Modbus device from C
2 min readThe wire format matters only when you can speak it from code; this lesson covers libmodbus and turning raw registers into usable values.
A TCP connection can succeed while your first register read fails. The connection gives your program a byte stream, as described in tcp(7). The server still has to recognise the Modbus request and provide the requested address range. Even a successful register read leaves a question for the application. Is the returned word a signed temperature, an unsigned setpoint, or one word of a larger counter? You answer that from the device map.
Include <modbus/modbus.h> and link with -lmodbus. For TCP, modbus_new_tcp(host, port) creates a context for the server endpoint. For RTU, modbus_new_rtu(device, baud, parity, data_bits, stop_bits) creates a context for a serial device with the supplied line settings. Both constructors return a context pointer or NULL. For an RTU client, call modbus_set_slave(ctx, address) to select the addressed device and check for a return of zero. A TCP gateway may also require a specific unit identifier to reach a device behind it. Set the identifier from the gateway's configuration. The direct TCP simulator below works with the default TCP unit identifier.
Call modbus_connect(ctx) and check for zero before issuing requests. The same register calls work through either context. modbus_read_registers(ctx, start, count, words) sends function 03, Read Holding Registers. Give it an array of uint16_t with room for at least count entries. The count is measured in registers. On success, the return value is the number of registers read. modbus_write_register(ctx, address, value) sends function 06, Write Single Register, and returns 1 on success. A failed request returns -1. Report the error promptly with modbus_strerror(errno), since subsequent calls can change errno. errno(3)
Treat the requested count as a condition for decoding. For example, decoding a two-register counter requires a return of 2 before either word is used. A local variable or buffer can still contain data from an earlier operation after a failed read. A successful connection by itself gives you no fresh register data. When finished, call modbus_close on the connected context and then modbus_free. If connection setup fails after the constructor succeeded, free the context.
Keep the libmodbus calls where device communication happens. Give the rest of the application names such as temperature_c, runtime_seconds, and setpoint_tenths. The polling code can change offsets for a different device model while callers continue to use the same named values. The same design lets you check conversion code with known register values before connecting to hardware.
Convert register words to application values
3 min readA register map needs enough detail to turn a successful read into a meaningful value. Record the register table, request offset, width in registers, type, units, scale, valid limits, and whether the application may write the field. For multi-register fields, record the word order and any device-specific byte swaps. If the manual specifies an invalid-data marker, record that too. Keep the map with the device model and firmware revision it describes.
The simulator in this lesson uses the following map. Its holding-register references use the convention in which 40001 means offset 0. Some manuals already list zero-based offsets, so confirm the addressing convention before converting anything. With the simulator's convention, 40003 becomes offset 2. The leading 4 identifies the holding-register table in this notation. The call to modbus_read_registers selects that table through the function code.
| Holding reference | Request offset | Field | Encoding and application limits |
|---|---|---|---|
| 40001 | 0 | Temperature | Signed 16-bit, tenths of a degree Celsius, −40.0 to 125.0 °C |
| 40002 | 1 | Setpoint | Unsigned 16-bit, tenths of a degree Celsius, 0.0 to 100.0 °C |
| 40003–40004 | 2–3 | Runtime | Unsigned 32-bit, high word first, seconds, 0 to 4,294,967,295 |
In this map the application writes only the setpoint. A holding register can expose a measurement that the application should only read. The simulator has a generic writable table, so the application has to enforce its own policy in this lab.
On the wire, each Modbus register travels with its high byte first. libmodbus assembles those two bytes into one uint16_t for you. A transmitted byte pair FF 85 therefore arrives in your array as the numeric word 0xFF85. Host and network byte order are distinct, as byteorder(3) explains. Applying ntohs to the word already returned by libmodbus would swap its bytes on a little-endian host.
The word 0xFF85 has an unsigned value of 65,413. The temperature map specifies a signed two's-complement value, so subtract 65,536 when bit 15 is set. This gives −123 raw tenths, or −12.3 °C. Let raw be the received uint16_t. A portable C expression for the signed count is raw >= 0x8000u ? (int32_t)raw - 65536 : (int32_t)raw. Check that the count is between −400 and 1250 inclusive before presenting it as a valid temperature. Dividing by 10.0 preserves the fractional digit. For device maps that specify an additive offset, apply it after scaling the signed or unsigned count.
For a 32-bit field, first identify the high and low words from the map. With high word first and words starting at offset 2, assemble the runtime as ((uint32_t)words[0] << 16) | words[1]. Cast before shifting so the shift takes place in an unsigned 32-bit type. The simulator stores 0x0001 followed by 0x2345, which decodes to 0x00012345, or 74,565 seconds. A low-word-first device would store those words in the opposite sequence. Some devices also lay out the bytes of a multi-register field differently within each word. Follow the documented byte layout and explicitly swap bytes within the affected words before assembly if the map calls for it. For a field specified as IEEE 754 binary32, assemble the documented 32-bit pattern first, then copy its bits to a compatible float with memcpy. A numeric cast from the assembled integer would convert the integer's magnitude.
A raw setpoint word can represent 0 through 65,535, but the application accepts 0 through 1000 tenths. An application that takes integer tenths can check the bounds before casting to uint16_t. If it accepts degrees as floating point, define a policy for values between tenths. For example, reject non-finite and out-of-range inputs, then round to the nearest tenth and check the encoded count. In either case, invalid input should produce no write request.
Read and write against a local simulator
4 min readUse two terminals in the same Ubuntu 24.04 environment. This simulator uses libmodbus's server API and keeps four holding registers in memory. It listens on the IPv4 loopback address 127.0.0.1, port 1502, and serves one client connection at a time. Its initial register values are explicit in the code, so you can compare decoded results against known inputs. Restarting the simulator restores those initial values.
sudo apt update
sudo apt install gcc libmodbus-dev
Save this as sim.c. modbus_mapping_new allocates the register table. modbus_receive receives a request into a buffer sized for a TCP Modbus message, and modbus_reply answers using the table. The table stays allocated across client connections, so a write remains visible to subsequent reads until the simulator exits.
#include <modbus/modbus.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
modbus_t *ctx = modbus_new_tcp("127.0.0.1", 1502);
if (ctx == NULL) {
perror("modbus_new_tcp");
return 1;
}
modbus_mapping_t *map = modbus_mapping_new(0, 0, 4, 0);
if (map == NULL) {
perror("modbus_mapping_new");
modbus_free(ctx);
return 1;
}
map->tab_registers[0] = 0xFF85;
map->tab_registers[1] = 200;
map->tab_registers[2] = 0x0001;
map->tab_registers[3] = 0x2345;
int listener = modbus_tcp_listen(ctx, 1);
if (listener >= 0) {
uint8_t request[MODBUS_TCP_MAX_ADU_LENGTH];
while (modbus_tcp_accept(ctx, &listener) >= 0) {
int n;
while ((n = modbus_receive(ctx, request)) >= 0) {
if (n > 0 && modbus_reply(ctx, request, n, map) == -1) {
perror("modbus_reply");
break;
}
}
modbus_close(ctx);
}
}
perror("simulator listen/accept");
if (listener >= 0 && close(listener) == -1) perror("close");
modbus_mapping_free(map);
modbus_free(ctx);
return 1;
}
gcc -Wall -Wextra -std=c17 sim.c -o sim -lmodbus
./sim
In the second terminal, start with the following client. It reads the existing setpoint, validates the requested count, writes it, and checks a fresh read of the same offset. Save it as client.c. The requested value is expressed in tenths, so 235 means 23.5 °C.
#include <errno.h>
#include <modbus/modbus.h>
#include <stdint.h>
#include <stdio.h>
int main(void)
{
const int requested = 235;
if (requested < 0 || requested > 1000) {
fputs("Setpoint outside allowed range\n", stderr);
return 1;
}
modbus_t *ctx = modbus_new_tcp("127.0.0.1", 1502);
if (ctx == NULL || modbus_connect(ctx) == -1) {
fprintf(stderr, "Setup: %s\n", modbus_strerror(errno));
if (ctx != NULL) modbus_free(ctx);
return 1;
}
uint16_t before, after;
int rc = modbus_read_registers(ctx, 1, 1, &before);
if (rc == 1)
rc = modbus_write_register(ctx, 1, (uint16_t)requested);
if (rc == 1)
rc = modbus_read_registers(ctx, 1, 1, &after);
int ok = 0;
if (rc == -1)
fprintf(stderr, "Request: %s\n", modbus_strerror(errno));
else if (rc != 1)
fputs("Unexpected register count\n", stderr);
else if (after != (uint16_t)requested)
fputs("Read-back mismatch\n", stderr);
else
ok = printf("Setpoint: %.1f -> %.1f C\n",
before / 10.0, after / 10.0) >= 0;
modbus_close(ctx);
modbus_free(ctx);
return ok ? 0 : 1;
}
gcc -Wall -Wextra -std=c17 client.c -o client -lmodbus
./client
From the simulator's initial values, the first run should read 20.0 °C before the write and 23.5 °C after it (this is what both programs printed on Ubuntu 24.04 with libmodbus 3.1.10, built with gcc -Wall -Wextra -std=c17 and no warnings). On a repeat run against the same simulator, the initial read should already show 23.5 °C. The value you see depends on what has been written since the simulator started. Reading back confirms the stored register value at that instant. On physical equipment, feedback that an actuator reached its target would come from a measurement or status field documented by the device.
When extending the client, read all four holding registers from offset 0 in one call. With that starting offset, the temperature is words[0], the setpoint is words[1], and the runtime occupies words[2] and words[3]. In a separate read starting at offset 2, the runtime instead occupies array indices 0 and 1. Array indices are relative to the start of the request. Checking both raw words and decoded values helps distinguish an addressing mistake from a mistake in signedness, scaling, or word order.
The next lesson, CAN frames, SocketCAN, and can-utils, shows how Linux programs send and receive CAN frames and where application-level interpretation fits when the interface delivers frame payloads.
Key takeaways
- libmodbus returns holding registers as host-order uint16_t values.
- A 32-bit field occupies two registers whose word order comes from the device map.
- Representable raw values and valid application values can have different limits.
- Reading a register back verifies its stored value at the time of the read.
Reflect
- Explain to a colleague, in two sentences: connect a libmodbus TCP client to a local simulator
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Docslibmodbus: a Modbus library for Linux
- Man pagetcp(7): the TCP socket interface
- Man pagebyteorder(3): host and network byte order
- Man pageerrno(3): error numbers and when to inspect them
Official documentation first. Links checked when the lesson was published.