Skip to content
You Start with one site
Amounts in Start with one site
Control, Measurement & Energy · Course

Modbus RTU: Frames, Function Codes and the CRC

Lesson 2 of 10 26 min read
Found this useful?

A gateway reports “timeout” for a meter, and the technician has three suspects: the cable, the serial settings and the request itself. Without the bytes, you change things until it works, and a day is lost. With the bytes, the answer often takes one minute, because a Modbus frame says who was asked, what was asked, and whether the answer arrived undamaged. Here you build a real request to an energy meter byte by byte, calculate its checksum, decode the response into volts and amperes, and read the short frame a device sends when it refuses a request. #ModbusRTU #CRC16 #IndustrialCommunication

Learning Objectives

By the end of this lesson, you will be able to:

  1. Describe the roles of client and server and the rule of one request and one response
  2. Build a Modbus RTU request frame from an address, a function code, a start address and a quantity
  3. Calculate the CRC-16 of a frame in Python and in C, and place its two bytes in the correct order
  4. Decode a normal response into register values, and an exception response into its cause
  5. Calculate the character time and the silent interval for a given baud rate

Real-World System Problem: Reading the compressor meter



A three-phase energy meter is fitted on the feeder of a cold store compressor. It has server address 5 on an RS-485 bus that it shares with a variable speed drive (address 10) and three more meters. A gateway at one end of the bus asks each device for its values in turn. The serial settings are 9600 baud, 8 data bits, even parity and 1 stop bit.

The meter holds its measurements in numbered 16-bit registers; the first nine are the three phase voltages, the three phase currents, the total active power, the power factor and the frequency. To get them, the gateway sends exactly eight bytes and the meter answers with exactly twenty-three. One wrong byte, or the two checksum bytes in the wrong order, and the meter stays silent.

When a reading is doubted, those bytes are the evidence: they show whether a strange value came from the meter, the wire, or the gateway’s own configuration.

Meters(more)Driveaddr 10Meteraddr 5Gatewayclientrequest to address 5response from address 5
One client asks, the addressed server answers

Fundamental Theory: One request, one response, one check



Client and server

Modbus has two roles. The client asks. A server answers. Older documents and many device manuals call them master and slave: the meaning is the same. On a serial bus there is one client, and every other device is a server with its own address from 1 to 247.

A server never speaks first. The client sends one request to one address and waits. That server sends one response, and every other server sees that the address is not its own and stays silent. So only one device sends at a time, and the two-wire bus never has two drivers active together.

This rule has a field consequence. Never connect a laptop as a second client to a bus that a gateway already polls: the two clients send at the same time, their requests collide, and both see timeouts on healthy meters. To look at a working bus, listen only (an adapter that never transmits), or let the gateway read for you.

The frame

A frame is one complete message on the wire. In Modbus RTU every frame, request or response, has the same four parts, like a sealed letter: who it is for, what to do, the details, and a seal that shows damage on the way.

Address1 byteFunction1 byteCRC-16low, highData0 to 252 byteswhowhatdetailsthe check
A Modbus RTU frame
  • The address names the server that must act or that is answering.
  • The function code says what to do.
  • The data depends on the function code.
  • The CRC is a 16-bit check value calculated from all the bytes before it.

A frame is at most 256 bytes. RTU sends raw binary bytes, not text. This lesson writes each byte as two hexadecimal digits, such as 0A, only so that people can read it.

Function codes and register kinds

Modbus organises a device’s data as four kinds of numbered item.

KindClassic numbersSizeAccessRead withWrite with
Coils0xxxx1 bitread and write0105
Discrete inputs1xxxx1 bitread only02none
Input registers3xxxx16 bitsread only04none
Holding registers4xxxx16 bitsread and write0306, 16

Functions 05 and 06 write a single coil or register. Function 16, which is 0x10, writes several registers in one frame.

Reading holding registers

The request for function 03 has four data bytes: the start address (two bytes) and the quantity of registers (two bytes). Modbus sends every 16-bit value with its high byte first.

Request fieldBytesContent
Address1Server address
Function10x03
Start address2Address of the first register, high byte first
Quantity2Number of registers , from 1 to 125
CRC2Low byte first

The normal response repeats the address and the function code, then gives a byte count and the register values.

Response fieldBytesContent
Address1Server address
Function10x03
Byte count1
Register valuesEach register high byte first, in address order
CRC2Low byte first

So a request is always 8 bytes, and a response for registers is bytes. The limit of 125 registers comes from the frame size: bytes.

Why a check is needed

A long cable in a plant room sometimes changes a bit. In a register value, that gives a wrong reading, and nothing in the value shows it. So the sender calculates a check value from the bytes of the frame and adds it at the end. The receiver calculates the same check from what it received and discards the frame if the two differ.

Modbus RTU uses a cyclic redundancy check of 16 bits, called CRC-16/MODBUS. The frame is treated as one long binary number and divided by a fixed 17-bit number, in a division where subtraction is replaced by exclusive OR (XOR). The remainder is the CRC. In practice the division is a short loop of shifts and XOR operations.

The CRC algorithm

Three constants define CRC-16/MODBUS: the initial value 0xFFFF, the polynomial 0xA001 (the bit-reversed form of 0x8005), and no change to the final value.

Follow the first byte of a request to address 5. The CRC starts at 0xFFFF, and the byte 0x05 is XORed in: , where means XOR. Then come eight shifts. Before each shift, look at the lowest bit: that is the bit that the shift pushes out.

ShiftBit pushed outXOR with 0xA001?CRC after
10no0x7FFD
21yes0x9FFF
31yes0xEFFE
40no0x77FF
51yes0x9BFE
60no0x4DFF
71yes0x86FE
80no0x437F

After the first byte the CRC is 0x437F. The second byte is XORed into that value, eight more shifts follow, and so on to the last byte before the CRC.

CRC-16/MODBUS

Initial value 0xFFFF. For each byte: XOR it into the low byte of the CRC, then eight times shift right, with an XOR by 0xA001 each time a 1 is pushed out. No final XOR. On the wire the low byte of the CRC is sent first, then the high byte.

A well-known check value lets you test any implementation. The six bytes 01 03 00 00 00 0A have the CRC 0xCDC5, so the frame on the wire ends with C5 CD. If your code does not give that, do not connect it to a bus.

The loop can be programmed two ways, with the same result. The bit-by-bit form above needs no memory. The table form calculates in advance what each of the 256 possible bytes does to the CRC, then handles a whole byte with one lookup: faster, at a cost of 512 bytes of memory.

What the CRC catches

This CRC detects every frame with one or two wrong bits, every frame with an odd number of wrong bits, and every burst of errors up to 16 bits long. Of heavier damage, about one case in 65,536 passes by chance. That is strong but not proof, so software should also reject an impossible value, such as a mains voltage of 6,553.5 V.

A receiver has a convenient test. If it runs the CRC over the whole frame, including the two CRC bytes, a good frame always gives 0x0000.

The CRC protects against accidents, not against people. Modbus has no authentication: any device on the bus can send a valid request, and a server obeys it. The standard answers are a separate network for control equipment, a gateway that only reads, and encryption on the link from the gateway upward.

Exception responses

A server that receives a good frame but cannot do what it asks sends an exception response. It is always five bytes: the address, the function code with its highest bit set (the function code plus 0x80), one exception code, and the CRC. For a refused function 03 the second byte is .

CodeNameUsual cause
01Illegal functionThe device does not support this function code
02Illegal data addressThe start address, or start plus quantity, is outside the device’s map
03Illegal data valueA value in the request is not allowed, such as a quantity of 0
04Server device failureThe device failed while it tried to act
05AcknowledgeThe request was accepted but takes a long time; ask again later
06Server device busyThe device is busy with a long task; send the request again later
0AGateway path unavailableSent by a gateway: it has no route to the server address
0BGateway target device failed to respondSent by a gateway: the serial server did not answer it

An exception and a silence mean different things.

  • An exception from the server itself (codes 01 to 06) proves that the cable, the baud rate, the parity, the address and the CRC are all correct. The fault is in what the request asks for. Codes 0A and 0B are different: they come from a gateway and prove only the link to the gateway. Code 0B is a timeout on the far side of it.
  • No response means the request did not arrive as a valid frame for any server. A server stays silent when the CRC or the parity is wrong, and when the address is not its own. The client learns this only when its timeout ends.

Character timing and the silent interval

RTU has no start byte and no end byte. Time marks the limits of a frame. The serial port sends each byte as one character: a start bit, eight data bits, a parity bit and a stop bit, 11 bits in total. (With no parity, the serial line guide asks for two stop bits, so a character is still 11 bits. Many devices are set to one stop bit with no parity, 8N1, instead: always set the client to the setting shown in the device’s own menu.)

Character time and silent interval

Frames are separated by a silence of at least . Inside a frame, no gap between two characters may be longer than .

At 9600 baud, , the silent interval is , and the largest gap inside a frame is . At 19200 baud the values halve: 0.573 ms, 2.01 ms and 0.859 ms. Above 19200 baud the serial line guide recommends fixed values of 1.750 ms between frames and 0.750 ms between characters, because the calculated times become too short for simple devices to measure.

lineidle0503000000098448050312..8 characters, 9.17 mssilence of4.01msormore
Silence separates the request from the response

The receiver works like a stopwatch that restarts at every character: a silence of 3.5 characters ends the frame and starts the CRC check. So the sender must give the whole frame to the serial port as one block. A program interrupted for 3 ms halfway through a frame has sent nothing useful: at 9600 baud the gap is 2.6 characters, more than 1.5, so the frame is discarded; at 19200 baud it is 5.2 characters, so the server sees two broken frames.

Broadcast

Address 0 is the broadcast address. Every server accepts a request sent to it and none answers, because several answers together would collide on the bus. So broadcast is only for writes, and since the client gets no confirmation, a broadcast write that matters must be checked afterwards by reading each device.

Application 1: Read nine registers from the compressor meter



Step 1: Build the request

Click to reveal the request frame
  1. Address. The meter is server 5: byte 05. ✅

  2. Function code. The values are holding registers, so the function is 03: byte 03. ✅

  3. Start address. Register 40001 is address 0x0000, sent high byte first: bytes 00 00. ✅

  4. Quantity. Registers 40001 to 40009 are registers, which is 0x0009: bytes 00 09. ✅

  5. CRC. Run the algorithm over the six bytes 05 03 00 00 00 09. The first byte gives 0x437F, as in the table of the theory section, and after the sixth byte the CRC is 0x4884. The low byte goes first: bytes 84 48. ✅

  6. Complete request.

    05 03 00 00 00 09 84 48

    Eight bytes. ✅

Step 2: Turn the readings into register values

Click to reveal the register values
  1. Divide each reading by its scaling. A register holds a whole number of counts. For the first voltage, counts. ✅

  2. Write each count in hexadecimal. , so the high byte is 0x09 and the low byte is 0x63: register value 0x0963. ✅

  3. All nine registers.

    RegisterReadingCountsHexBytes sent
    40001240.3 V24030x096309 63
    40002239.8 V23980x095E09 5E
    40003241.1 V24110x096B09 6B
    4000440.12 A40120x0FAC0F AC
    4000539.87 A39870x0F930F 93
    4000640.31 A40310x0FBF0F BF
    4000724.15 kW24150x096F09 6F
    400080.8408400x034803 48
    4000950.02 Hz50020x138A13 8A

    Each register is sent high byte first. ✅

Step 3: Build the response

Click to reveal the response frame
  1. Address and function. The meter repeats them: bytes 05 03. ✅

  2. Byte count. Nine registers of two bytes: , which is 0x12: byte 12. ✅

  3. Register values. The eighteen bytes of Step 2, in address order. ✅

  4. CRC. The algorithm over the first 21 bytes gives 0x6441, sent as 41 64. ✅

  5. Complete response.

    05 03 12 09 63 09 5E 09 6B 0F AC 0F 93 0F BF 09 6F
    03 48 13 8A 41 64

    The length is bytes. (The frame is one unbroken run of bytes. It is printed on two lines only to fit the page.) ✅

Step 4: Time on the bus

Click to reveal the timing
  1. Character time. . ✅

  2. Request. . ✅

  3. Response. . ✅

  4. Silent interval. at least, before and after each frame. ✅

Step 5: Check by decoding the response

Click to reveal the check
  1. Check the CRC as a receiver does. The script runs the CRC over the 21 bytes before the CRC and compares the result with the last two bytes. They match, and the frame is accepted. ✅

  2. Check the header. Address 5 is the server that was asked. Function 0x03 has no high bit set, so this is a normal response. The byte count of 18 agrees with the nine registers requested. ✅

  3. Decode the values. The script joins each pair of bytes, high byte first, and multiplies by the scaling. It returns 240.3 V, 239.8 V, 241.1 V, 40.12 A, 39.87 A, 40.31 A, 24.15 kW, 0.840 and 50.02 Hz: the readings of the problem. ✅

  4. Check the values against each other. For a balanced load, , using the mean voltage and current. That is 24.3 kW against the 24.15 kW in register 40007, a difference of 0.6 percent. The decoded frame describes one believable machine. ✅

  5. Check against the meter itself. At commissioning, read the meter’s own display at the same moment. The voltage there must agree with the decoded 240.3 V within the last digit it shows. A value 10 or 100 times too large is a scaling error. A plausible value that belongs to another quantity (a current where a voltage should be) is a register read one place out. ✅

Application 2: Decode a captured exception response



Step 1: Is the response a valid frame?

Click to reveal the CRC check
  1. Separate the CRC. The response has five bytes. The last two, 81 30, are the CRC with the low byte first, so the received CRC is 0x3081. ✅

  2. Calculate the CRC of the first three bytes. The algorithm over 05 83 02 gives 0x3081. The values match, so the frame arrived undamaged. ✅

  3. What this already proves. A valid response from address 5 means the cable, the baud rate, the parity and the address are all correct. The fault is not electrical. ✅

Step 2: Decode the response

Click to reveal the decoding
  1. Address. 05: the meter answered. ✅

  2. Function code. 83 has its highest bit set. Remove 0x80: . This is an exception response to a function 03 request. ✅

  3. Exception code. 02: illegal data address. The meter does not have the register that was asked for. ✅

Step 3: What was wrong with the request?

Click to reveal the diagnosis
  1. Decode the request. Address 05, function 03, start address 00 64, quantity 00 02. Its own CRC, 84 50, is correct, because the meter answered. ✅

  2. Start address as a register number. , and address 100 is holding register . The request asks for registers 40101 and 40102. ✅

  3. Compare with the maps. The meter’s map ends at address 0x000D, so address 0x0064 does not exist in the meter. Registers 40101 and 40102 are the speed reference and the control word of the drive. ✅

  4. Diagnosis. The poll item is correct in function, start address and quantity, but it carries the server address of the meter (5) in place of the address of the drive (10). ✅

  5. Corrected request. Change the first byte to 0x0A and calculate the CRC again, because every byte of the frame is inside the CRC:

    0A 03 00 64 00 02 84 AF

    This reads the two registers from the drive. It is a read, so it cannot start the machine. ✅

  6. Check a second way. The script builds the exception frame from its three bytes and confirms the CRC bytes 81 30. It also changes one bit of a good response and shows that the CRC check then fails. ✅

Verify It in Python



The script calculates the CRC bit by bit and by table and tests both on the check frame. It builds and decodes the frames of both applications, calculates the character timing, and saves a plot of the request as logic levels on the wire.

modbus_rtu_frames.py
"""Modbus RTU: the CRC two ways, a request and a response for meter A, an exception."""
import numpy as np
import matplotlib.pyplot as plt
def crc16_bitwise(data):
"""CRC-16/MODBUS, one bit at a time."""
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x0001:
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
return crc
def make_table():
"""The 256 values a byte can add to the CRC, calculated once."""
table = []
for value in range(256):
crc = value
for _ in range(8):
crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1
table.append(crc)
return table
TABLE = make_table()
def crc16_table(data):
"""CRC-16/MODBUS, one byte at a time with the table."""
crc = 0xFFFF
for byte in data:
crc = (crc >> 8) ^ TABLE[(crc ^ byte) & 0xFF]
return crc
def add_crc(body):
"""Return the frame: body, then CRC low byte, then CRC high byte."""
crc = crc16_bitwise(body)
return bytes(body) + bytes([crc & 0xFF, crc >> 8])
def crc_ok(frame):
"""True when the last two bytes are the CRC of the bytes before them."""
return add_crc(frame[:-2]) == bytes(frame)
def hexs(data):
return " ".join(f"{b:02X}" for b in data)
# ---------- Part 1: the well-known check frame ----------
check = bytes([0x01, 0x03, 0x00, 0x00, 0x00, 0x0A])
print("Check frame", hexs(check))
print(f" bit by bit: 0x{crc16_bitwise(check):04X}, by table: 0x{crc16_table(check):04X}")
print(f" on the wire: {hexs(add_crc(check))}")
assert hexs(add_crc(check)).endswith("C5 CD")
assert all(crc16_bitwise(bytes([i, 255 - i, 7])) == crc16_table(bytes([i, 255 - i, 7]))
for i in range(256))
# ---------- Part 2: the first byte of the meter request, step by step ----------
crc = 0xFFFF ^ 0x05
print(f"First byte 0x05: 0xFFFF XOR 0x05 = 0x{crc:04X}")
for shift in range(1, 9):
low_bit = crc & 1
crc = (crc >> 1) ^ 0xA001 if low_bit else crc >> 1
print(f" shift {shift}: bit out {low_bit}, CRC 0x{crc:04X}")
# ---------- Part 3: request to meter A ----------
ADDRESS, FUNCTION, START, QUANTITY = 5, 0x03, 0x0000, 9
request = add_crc([ADDRESS, FUNCTION, START >> 8, START & 0xFF,
QUANTITY >> 8, QUANTITY & 0xFF])
print("Request ", hexs(request),
f"({len(request)} bytes, CRC 0x{crc16_table(request[:-2]):04X})")
# ---------- Part 4: response for the example readings ----------
names = ["V L1-N", "V L2-N", "V L3-N", "I L1", "I L2", "I L3",
"P total", "PF", "f"]
units = ["V", "V", "V", "A", "A", "A", "kW", "", "Hz"]
scale = [0.1, 0.1, 0.1, 0.01, 0.01, 0.01, 0.01, 0.001, 0.01]
signed = [False] * 6 + [True, True, False]
readings = [240.3, 239.8, 241.1, 40.12, 39.87, 40.31, 24.15, 0.840, 50.02]
counts = [int(round(r / s)) for r, s in zip(readings, scale)]
body = [ADDRESS, FUNCTION, 2 * QUANTITY]
for c in counts:
body += [(c >> 8) & 0xFF, c & 0xFF]
response = add_crc(body)
print("Response", hexs(response),
f"({len(response)} bytes, CRC 0x{crc16_table(response[:-2]):04X})")
# ---------- Part 5: decode the response as a client does ----------
print("Decode: CRC good" if crc_ok(response) else "Decode: CRC bad")
print(f" address {response[0]}, function 0x{response[1]:02X}, byte count {response[2]}")
for i in range(response[2] // 2):
raw = (response[3 + 2 * i] << 8) | response[4 + 2 * i]
value = raw - 65536 if signed[i] and raw > 32767 else raw
print(f" 4{i + 1:04d} 0x{raw:04X} = {value:>5} -> "
f"{value * scale[i]:.3f} {units[i]} ({names[i]})")
# ---------- Part 6: an exception response ----------
bad_request = add_crc([5, 0x03, 0x00, 0x64, 0x00, 0x02])
exception = add_crc([5, 0x03 | 0x80, 0x02])
print("Bad request", hexs(bad_request))
print("Exception ", hexs(exception), "CRC good" if crc_ok(exception) else "CRC bad")
print(f" function 0x{exception[1]:02X} = 0x{exception[1] & 0x7F:02X} + 0x80, "
f"exception code {exception[2]:02d}")
print("Corrected ", hexs(add_crc([10, 0x03, 0x00, 0x64, 0x00, 0x02])))
damaged = bytearray(response)
damaged[4] ^= 0x04
print("One bit changed in the response: CRC",
"good" if crc_ok(damaged) else "bad, frame rejected")
# ---------- Part 7: character timing ----------
BITS = 11
for baud in (9600, 19200):
t_char = BITS / baud
print(f"{baud} baud: character {1e3 * t_char:.3f} ms, "
f"1.5 characters {1e3 * 1.5 * t_char:.3f} ms, "
f"3.5 characters {1e3 * 3.5 * t_char:.3f} ms, "
f"request {1e3 * len(request) * t_char:.2f} ms, "
f"response {1e3 * len(response) * t_char:.2f} ms")
# ---------- Plot: the request on the wire at 9600 baud, 8E1 ----------
levels = []
for byte in request:
data = [(byte >> i) & 1 for i in range(8)]
levels += [0] + data + [sum(data) % 2] + [1]
idle = [1] * 20
wave = np.array(idle + levels + idle)
t_ms = np.arange(len(wave) + 1) * 1e3 / 9600 - len(idle) * 1e3 / 9600
fig, ax = plt.subplots(figsize=(9, 3))
ax.step(t_ms, np.append(wave, wave[-1]), where="post")
for k, byte in enumerate(request):
ax.text((k + 0.5) * BITS * 1e3 / 9600, 1.15, f"{byte:02X}", ha="center")
ax.set_ylim(-0.2, 1.4)
ax.set_yticks([0, 1])
ax.set_xlabel("time (ms)")
ax.set_ylabel("logic level")
ax.set_title("Request to meter A on the wire: 8 characters of 11 bits, 9600 baud")
fig.tight_layout()
fig.savefig("modbus_rtu_frames.png", dpi=120)
print("Saved modbus_rtu_frames.png")

Expected output

Check frame 01 03 00 00 00 0A
bit by bit: 0xCDC5, by table: 0xCDC5
on the wire: 01 03 00 00 00 0A C5 CD
First byte 0x05: 0xFFFF XOR 0x05 = 0xFFFA
shift 1: bit out 0, CRC 0x7FFD
shift 2: bit out 1, CRC 0x9FFF
shift 3: bit out 1, CRC 0xEFFE
shift 4: bit out 0, CRC 0x77FF
shift 5: bit out 1, CRC 0x9BFE
shift 6: bit out 0, CRC 0x4DFF
shift 7: bit out 1, CRC 0x86FE
shift 8: bit out 0, CRC 0x437F
Request 05 03 00 00 00 09 84 48 (8 bytes, CRC 0x4884)
Response 05 03 12 09 63 09 5E 09 6B 0F AC 0F 93 0F BF 09 6F 03 48 13 8A 41 64 (23 bytes, CRC 0x6441)
Decode: CRC good
address 5, function 0x03, byte count 18
40001 0x0963 = 2403 -> 240.300 V (V L1-N)
40002 0x095E = 2398 -> 239.800 V (V L2-N)
40003 0x096B = 2411 -> 241.100 V (V L3-N)
40004 0x0FAC = 4012 -> 40.120 A (I L1)
40005 0x0F93 = 3987 -> 39.870 A (I L2)
40006 0x0FBF = 4031 -> 40.310 A (I L3)
40007 0x096F = 2415 -> 24.150 kW (P total)
40008 0x0348 = 840 -> 0.840 (PF)
40009 0x138A = 5002 -> 50.020 Hz (f)
Bad request 05 03 00 64 00 02 84 50
Exception 05 83 02 81 30 CRC good
function 0x83 = 0x03 + 0x80, exception code 02
Corrected 0A 03 00 64 00 02 84 AF
One bit changed in the response: CRC bad, frame rejected
9600 baud: character 1.146 ms, 1.5 characters 1.719 ms, 3.5 characters 4.010 ms, request 9.17 ms, response 26.35 ms
19200 baud: character 0.573 ms, 1.5 characters 0.859 ms, 3.5 characters 2.005 ms, request 4.58 ms, response 13.18 ms
Saved modbus_rtu_frames.png

The same CRC in C

Most servers are small microcontrollers programmed in C. The function below is the bit-by-bit algorithm. It compiles without warnings with gcc -Wall -Wextra -std=c11.

crc16_modbus.c
/* CRC-16/MODBUS and the request to meter A. */
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
static uint16_t crc16_modbus(const uint8_t *data, size_t length)
{
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < length; i++) {
crc ^= data[i];
for (int bit = 0; bit < 8; bit++) {
if (crc & 0x0001u) {
crc = (uint16_t)((crc >> 1) ^ 0xA001u);
} else {
crc = (uint16_t)(crc >> 1);
}
}
}
return crc;
}
/* Write the CRC after the body, low byte first. Returns the frame length. */
static size_t add_crc(uint8_t *frame, size_t body_length)
{
uint16_t crc = crc16_modbus(frame, body_length);
frame[body_length] = (uint8_t)(crc & 0xFFu);
frame[body_length + 1] = (uint8_t)(crc >> 8);
return body_length + 2;
}
static void print_frame(const char *label, const uint8_t *frame, size_t length)
{
printf("%s", label);
for (size_t i = 0; i < length; i++) {
printf(" %02X", frame[i]);
}
printf("\n");
}
int main(void)
{
uint8_t check[8] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x0A};
uint8_t request[8] = {0x05, 0x03, 0x00, 0x00, 0x00, 0x09};
size_t n;
n = add_crc(check, 6);
print_frame("Check frame:", check, n);
n = add_crc(request, 6);
print_frame("Request: ", request, n);
/* A receiver runs the CRC over the whole frame. A good frame gives 0. */
printf("CRC over the whole request: 0x%04X\n",
(unsigned)crc16_modbus(request, n));
return 0;
}

Expected output

Check frame: 01 03 00 00 00 0A C5 CD
Request: 05 03 00 00 00 09 84 48
CRC over the whole request: 0x0000

The last line shows the receiver’s test: the CRC over a whole good frame, including its own CRC bytes, is zero.

Common Mistakes



  • Sending the CRC high byte first because every other field is sent that way. The CRC is the exception: low byte first.
  • Putting the register number in the address field. Register 40001 is address 0x0000: subtract 40001, not 40000.
  • Treating an exception response as a communication failure. It is proof that communication works. Read the code.
  • Calculating the CRC over the text “05 03 00 …” in place of the raw bytes, one byte for each pair of hexadecimal digits.
  • Sending a frame in pieces with pauses between them. A gap longer than 1.5 characters inside a frame makes the receiver discard it.
  • Expecting an answer to a broadcast. Servers act on address 0 and stay silent.

Summary



  • Modbus has one client that asks and servers that answer. A server never speaks first, and each request gets one response from the addressed server.
  • An RTU frame is the address, the function code, the data and a CRC-16. All 16-bit values are sent high byte first, except the CRC, which is sent low byte first.
  • CRC-16/MODBUS starts at 0xFFFF and uses the polynomial 0xA001. The bytes 01 03 00 00 00 0A give C5 CD on the wire.
  • The request 05 03 00 00 00 09 84 48 reads nine registers from the compressor meter, and the 23-byte response carries them with a byte count of 18.
  • An exception response is five bytes with the function code plus 0x80. From the server itself, it proves the wire is good and names what the request asked wrongly. Codes 0A and 0B come from a gateway.
  • A character is 11 bits. Frames are separated by 3.5 character times of silence: 4.01 ms at 9600 baud.

Exercises



1. Build the request that reads the four holding registers 40201 to 40204 from the drive at address 10, with its CRC.

Answer

Register 40201 is address and the quantity is 4, so the body is 0A 03 00 C8 00 04. Its CRC is 0x8CC4, sent low byte first. The frame is 0A 03 00 C8 00 04 C4 8C.

2. A client reads 20 holding registers in one request. How many bytes is the response, and how long does it occupy the bus at 9600 baud? What is the longest possible response to function 03?

Answer

bytes, which take . The longest response is for 125 registers: bytes.

3. A client sends 05 03 00 08 00 01 04 4C to the meter of Application 1 and receives 05 03 02 13 88 44 D2. Which register was read, and what is the reading?

Answer

Start address 0x0008 with a quantity of 1 is register 40009, the frequency. The byte count is 2 and the value is counts. At 0.01 Hz per count the reading is 50.00 Hz. The CRC of 05 03 02 13 88 is 0xD244, which matches the bytes 44 D2.

4. A client receives 0A 86 03 73 A3. Which server answered, which function did it refuse, and why?

Answer

Server 10 (0x0A), the drive. , a write to a single register. Exception code 03 is illegal data value: the register exists, but the drive does not accept the value that was sent. The CRC of 0A 86 03 is 0xA373, which matches 73 A3, so the frame is valid.

5. A client receives the seven bytes 05 03 02 13 8A 44 D2. Calculate the CRC and decide whether to accept the frame. If the client had no CRC check, what frequency would it store?

Answer

The CRC of 05 03 02 13 8A is 0x13C5, which would be sent as C5 13. The frame ends with 44 D2, so it is damaged and must be discarded. Without the check, the client would store counts, 50.02 Hz, in place of the 0x1388, 50.00 Hz, that was sent (one bit of the fifth byte has changed). A range check cannot catch an error this small. The CRC does.

References



  • Modbus Organization, MODBUS Application Protocol Specification V1.1b3, 2012.
  • Modbus Organization, MODBUS over Serial Line Specification and Implementation Guide V1.02, 2006.
  • W. W. Peterson and D. T. Brown, “Cyclic Codes for Error Detection”, Proceedings of the IRE, vol. 49, no. 1, 1961.


© 2021-2026 SiliconWit®. All rights reserved.
Gatewayclientrequest to address 5Meteraddress 5Driveaddress 10Moremetersresponse from address 5
One client asks, the addressed server answers
Address1 bytewhoFunction1 bytewhatData0 to 252 bytesdetailsCRC-16low, highthe check
A Modbus RTU frame
Predict first

A manual says that the first voltage of a meter is in holding register 40001. The request has a field of two bytes for the start address. Which two bytes go in that field?

See it: build a request, byte by byte
Request from the client

Request length
On the wire at 9600 baud
On the wire at 19200 baud
CRC of the bytes before it
Response length
Response at 9600 / 19200 baud

Each box is one byte on the wire, written as two hexadecimal digits. The colour and the word under a box give its field. The CRC is calculated on this page from the bytes before it, with the algorithm of the lesson, and its low byte is sent first. The times count 11 bits for each character. The answer is that of the lesson's meter at address 5, with its example readings. The meter's map ends at address 0x000D. Register 40010 is not in the map, and this figure shows it as 0. The lesson gives no answer of the meter to function 04 or to a write, so none is shown. Nothing here is sent to any device: the figure only calculates.

Check yourself

Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.

1. The request 05 03 00 64 00 02 84 50 went to the meter by mistake. It must go to the drive at address 10. Which frame is correct?

2. A gateway shows a red mark for one item of its poll list. A capture shows that the meter answered 05 83 02 81 30. What should the technician check first?

3. The meter answers a read of nine registers with 23 bytes. The bus runs at 9600 baud with even parity. How long does the response occupy the bus?

050300 00 00 0984 48 to whomwhat to dothe detailsthe seal Broken seal: thrown away, no answer.
gatewaymetergatewaymeter 05 83 02 silence wire goodfix the requestno answercheck wire, settings, address
See it: silence marks where a frame ends

One character, 11 bits
Silence between frames, at least
Longest gap inside a frame

The receiver has no start or end byte to look for. It has a stopwatch that starts again at every character. When the silence reaches 3.5 character times, the frame has ended and the CRC is checked. A gap of more than 1.5 inside a frame breaks it.

Watch it build: the CRC of one request
05 03 00 00 00 09 ?? CRC after each byte: 437F E1423161E8F044E84884 8448 CRC = FFFFstart FFFF, polynomial A001 FFFF XOR 05 = FFFAXOR the byte into the low byte FFFA → 437Fbits out: 0 1 1 0 1 0 1 0each 1: shift, then XOR A001 CRC = 4884the same loop for each byte 84 48 on the wirelow byte of the CRC first all 8 bytes → 00000000: the frame arrived intact
  1. The request 05 03 00 00 00 09 needs its seal. The CRC register starts at FFFF.
  2. The first byte, 05, is XORed into the low byte: FFFF XOR 0005 = FFFA.
  3. Eight shifts. Each time a 1 is pushed out, XOR with A001. After the first byte: 437F.
  4. The same for the other five bytes. After the sixth byte the CRC is 4884.
  5. The CRC goes on the wire low byte first: 84 48. The frame is now 8 bytes.
  6. The receiver runs the CRC over all 8 bytes, CRC included. A good frame gives 0000.
Found this useful?

Discussion

    Comments show your name. Be kind, stay on the topic.