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:
Describe the roles of client and server and the rule of one request and one response
Build a Modbus RTU request frame from an address, a function code, a start address and a quantity
Calculate the CRC-16 of a frame in Python and in C, and place its two bytes in the correct order
Decode a normal response into register values, and an exception response into its cause
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.
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.
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.
Kind
Classic numbers
Size
Access
Read with
Write with
Coils
0xxxx
1 bit
read and write
01
05
Discrete inputs
1xxxx
1 bit
read only
02
none
Input registers
3xxxx
16 bits
read only
04
none
Holding registers
4xxxx
16 bits
read and write
03
06, 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 field
Bytes
Content
Address
1
Server address
Function
1
0x03
Start address
2
Address of the first register, high byte first
Quantity
2
Number of registers , from 1 to 125
CRC
2
Low byte first
The normal response repeats the address and the function code, then gives a byte count and the register values.
Response field
Bytes
Content
Address
1
Server address
Function
1
0x03
Byte count
1
Register values
Each register high byte first, in address order
CRC
2
Low 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.
Shift
Bit pushed out
XOR with 0xA001?
CRC after
1
0
no
0x7FFD
2
1
yes
0x9FFF
3
1
yes
0xEFFE
4
0
no
0x77FF
5
1
yes
0x9BFE
6
0
no
0x4DFF
7
1
yes
0x86FE
8
0
no
0x437F
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 .
Code
Name
Usual cause
01
Illegal function
The device does not support this function code
02
Illegal data address
The start address, or start plus quantity, is outside the device’s map
03
Illegal data value
A value in the request is not allowed, such as a quantity of 0
04
Server device failure
The device failed while it tried to act
05
Acknowledge
The request was accepted but takes a long time; ask again later
06
Server device busy
The device is busy with a long task; send the request again later
0A
Gateway path unavailable
Sent by a gateway: it has no route to the server address
0B
Gateway target device failed to respond
Sent 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.
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
Address. The meter is server 5: byte 05. ✅
Function code. The values are holding registers, so the function is 03: byte 03. ✅
Start address. Register 40001 is address 0x0000, sent high byte first: bytes 00 00. ✅
Quantity. Registers 40001 to 40009 are registers, which is 0x0009: bytes 00 09. ✅
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. ✅
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
Divide each reading by its scaling. A register holds a whole number of counts. For the first voltage, counts. ✅
Write each count in hexadecimal., so the high byte is 0x09 and the low byte is 0x63: register value 0x0963. ✅
All nine registers.
Register
Reading
Counts
Hex
Bytes sent
40001
240.3 V
2403
0x0963
09 63
40002
239.8 V
2398
0x095E
09 5E
40003
241.1 V
2411
0x096B
09 6B
40004
40.12 A
4012
0x0FAC
0F AC
40005
39.87 A
3987
0x0F93
0F 93
40006
40.31 A
4031
0x0FBF
0F BF
40007
24.15 kW
2415
0x096F
09 6F
40008
0.840
840
0x0348
03 48
40009
50.02 Hz
5002
0x138A
13 8A
Each register is sent high byte first. ✅
Step 3: Build the response
Click to reveal the response frame
Address and function. The meter repeats them: bytes 05 03. ✅
Byte count. Nine registers of two bytes: , which is 0x12: byte 12. ✅
Register values. The eighteen bytes of Step 2, in address order. ✅
CRC. The algorithm over the first 21 bytes gives 0x6441, sent as 41 64. ✅
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
Character time.. ✅
Request.. ✅
Response.. ✅
Silent interval. at least, before and after each frame. ✅
Step 5: Check by decoding the response
Click to reveal the check
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. ✅
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. ✅
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. ✅
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. ✅
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
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. ✅
Calculate the CRC of the first three bytes. The algorithm over 05 83 02 gives 0x3081. The values match, so the frame arrived undamaged. ✅
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
Address.05: the meter answered. ✅
Function code.83 has its highest bit set. Remove 0x80: . This is an exception response to a function 03 request. ✅
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
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. ✅
Start address as a register number., and address 100 is holding register . The request asks for registers 40101 and 40102. ✅
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. ✅
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). ✅
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. ✅
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
defcrc16_bitwise(data):
"""CRC-16/MODBUS, one bit at a time."""
crc =0xFFFF
for byte in data:
crc ^= byte
for _ inrange(8):
if crc &0x0001:
crc = (crc >>1) ^0xA001
else:
crc >>=1
return crc
defmake_table():
"""The 256 values a byte can add to the CRC, calculated once."""
table =[]
for value inrange(256):
crc = value
for _ inrange(8):
crc = (crc >>1) ^0xA001if crc &1else crc >>1
table.append(crc)
return table
TABLE=make_table()
defcrc16_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
defadd_crc(body):
"""Return the frame: body, then CRC low byte, then CRC high byte."""
crc =crc16_bitwise(body)
returnbytes(body) +bytes([crc &0xFF, crc >>8])
defcrc_ok(frame):
"""True when the last two bytes are the CRC of the bytes before them."""
returnadd_crc(frame[:-2]) ==bytes(frame)
defhexs(data):
return"".join(f"{b:02X}"for b in data)
# ---------- Part 1: the well-known check frame ----------
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.
/* 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));
return0;
}
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.
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.
One client asks, the addressed server answers
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
Answer of the meter at address 5
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?
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
The request 05 03 00 00 00 09 needs its seal. The CRC register starts at FFFF.
The first byte, 05, is XORed into the low byte: FFFF XOR 0005 = FFFA.
Eight shifts. Each time a 1 is pushed out, XOR with A001. After the first byte: 437F.
The same for the other five bytes. After the sixth byte the CRC is 4884.
The CRC goes on the wire low byte first: 84 48. The frame is now 8 bytes.
The receiver runs the CRC over all 8 bytes, CRC included. A good frame gives 0000.
Found this useful?
Discussion
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
Text size
←→
Previous and next card. On a turned card: Not yet, I knew it
SpaceEnter
Turn the card, show the answer
123
Overview, Recap, Test me
HomeEnd
First and last card
Esc
Close
← → or scroll · N notes · F full screen · B blank0:00
My notes on this page
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
Notes on earlier wording
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.