02 — THE MODBUS TCP FRAME

The byte-level shape of every Modbus TCP message.

Estimated 8 minutes.

Every message is a small string of bytes.

A single Modbus TCP message is a short, fixed-shape buffer: an envelope on the front (the MBAP header) and a payload on the back (the PDU). Once you can name the parts, the protocol stops feeling mysterious.

MBAP + PDU.

7 bytes of envelope, then 1 byte of function code, then up to 252 bytes of data.

The 7-byte MBAP header.

MBAP = Modbus Application Protocol header. It is the address envelope: which conversation is this, who is it for, and how long is the payload behind it. Always exactly 7 bytes, always at the front.

Inside the MBAP.

Transaction ID (2 B) · Protocol ID (2 B, always 0) · Length (2 B) · Unit ID (1 B).

Then the PDU.

PDU = Protocol Data Unit. One byte of function code (the "verb") followed by zero to 252 bytes of data that depend on which function was used.

Inside the PDU.

1 byte tells the slave what to do. Everything after is the data the function needs.

Build the frame.

Drag the labeled chips — TID, PID, length, unit ID, function, data — into the right slots until the frame is valid.

There is a hard ceiling.

Total message size is bounded: 7 bytes of MBAP + 1 byte of function + at most 252 bytes of data = 260 bytes. That is why every Modbus operation has a max-count limit (125 registers, 2000 coils, etc.).

Why is the protocol ID always 0?

PID sits in every MBAP header and is always 0x0000. Why bother sending it?

  • It is a checksum byte
  • Reserved for future Modbus variants — kept 0 today
  • It identifies the IP version

Transaction ID matches replies to requests.

A master can have several requests in flight at the same time. Each one gets a unique transaction ID; the slave copies that same TID into the response. The master uses it to pair them back up.

Two requests in flight.

Master sends request A with TID 0x0001 and request B with TID 0x0002. The slave answers B first. How does the master know which response is which?

  • It checks the order the responses arrived
  • It reads the TID in the response header
  • It uses a separate TCP connection per request

You can read a Modbus frame end-to-end.

  • Every message = MBAP (7 B) + PDU (function + data).
  • MBAP fields: TID, PID, length, unit ID.
  • Total size capped at 260 bytes.
  • The TID is how a master matches replies to requests.

Lesson 02 complete.

  • You can label every byte in a Modbus TCP frame.
  • You can explain why the protocol ID is always zero.
  • You understand how transaction IDs let requests overlap.