
Lesson 12
Modbus TCP for PLC Programmers: Registers, Off-by-One and Timeouts
The four Modbus tables and the off-by-one, sixteen bits at a time, setting up a driver, what to do when no answer comes, and a handshake between two controllers.
From Usta's field manual in Meridian Works, a story-driven PLC course: chapter 12, “Communications”. Modbus TCP, and all the trouble with a number somebody else owns.
A number you did not measure
Every value you have used so far came from a terminal on an input card. Sometimes it was wrong: a wire broke, a transmitter drifted. But the value was yours. It came in when the inputs were read at the start of each scan, and it was as fresh as it could be.
This chapter is about the other kind. This number comes from a machine that is not yours. It travels down a cable you did not run. It arrives at a moment you did not choose.
Nothing here is instantaneous. The controller sends a request. A few milliseconds later, sometimes a few hundred, the answer comes back. Only then does the tag change. In between, the program has scanned twenty times, perhaps two hundred. Every one of those scans read the previous answer. No hardware or software removes this. All you can do is know how old the number is.
Client and server. In Modbus TCP one side asks and the other answers. The side that asks is the client (the old name is master); the side that answers is the server (the old name is slave). MASTER and SLAVE in the figure are these two. A server never speaks on its own. Even if it has a fault, it tells nobody until somebody asks. So the freshness of every value on the network is your decision. That decision is made in a field called "poll interval", often in a hurry.
Modbus TCP on the two platforms. Both lines can speak this protocol, but not in the same way.
- On Siemens there are ready-made instructions: MB_CLIENT for the client and MB_SERVER for the server. Both are blocks called inside the program.
- On Rockwell, ControlLogix and CompactLogix have no built-in Modbus TCP instruction. Rockwell publishes a sample Modbus TCP AOI that works over a socket. On site, a gateway module is also often used instead.
The driver in this app is a settings page. The field names change from platform to platform. The decisions you make do not.
Why one protocol. This chapter covers Modbus TCP only. PROFINET, EtherNet/IP and the rest differ in the easy parts: the cable, the names, the configuration tool. The hard parts turn up in all of them in some form:
- The value in your tag is always a little old.
- Nobody agreed how a 32-bit number is laid out.
- The far end may say "no".
- One day it says nothing, and nothing in your tags changes.
Learn these four on the simplest protocol there is. The rest is paperwork.
Four tables, and the off-by-one
Modbus has no tags, no data types and no names. It has four flat tables of numbers. A device's manual is a list of which piece of information sits in which table.
Two of the tables hold single bits, and two hold 16-bit registers. Two are read-only, and two can be written. That is the whole address space. A temperature, a recipe number, a motor's running state and a fault code each sit in one of these tables. The device's designer decided which.
Now the thing that costs everybody an afternoon.
Manuals write addresses as five-digit reference numbers: 40001, 30002, 10005. These numbers start at 1, and the leading digit names the table. The address that goes down the cable starts at 0. The table travels in the function code, not in the address.
So:
| in the manual | table | address sent |
|---|---|---|
| 40001 | holding | 0 |
| 40002 | holding | 1 |
| 30001 | input | 0 |
| 10008 | discrete | 7 |
| 00001 | coil | 0 |
40001 is register zero. Getting this wrong gives no error. It gives you the register next door. That is a valid number too, but it is the number of something else.
Drivers handle this differently. Check which form each new driver wants.
- On Siemens, MB_CLIENT wants the manual's number. You write 40001 into its MB_DATA_ADDR input. The instruction converts it to holding register 0 itself.
- On Rockwell, the sample AOI's or the gateway module's own documents say which form it wants. One wants 40001, another wants 0.
- The driver in this app wants the address that goes down the cable. You choose the table separately and write 0 as the address.
The function codes. They will be in the error message you read at three in the morning:
| FC | does |
|---|---|
| 1 | read coils |
| 2 | read discrete inputs |
| 3 | read holding registers |
| 4 | read input registers |
| 5 | write one coil |
| 6 | write one holding register |
| 15 | write several coils |
| 16 | write several holding registers |
You do not choose these directly here. The table and the direction (read or write) choose them for you. But you will meet them in somebody else's logs. Asking with FC 3 a device that only answers FC 4 is the second afternoon everybody loses.
Sixteen bits at a time
A register is sixteen bits. The protocol tells you nothing more. What those sixteen bits mean is in the manual. If the manual is wrong, or you read it in a hurry, nothing warns you.
Signed or unsigned. The same sixteen bits are 65530 read as a UINT and −6 read as an INT. A weight cannot be negative. So the weigher's designer may have used the unsigned range. A temperature can be negative. So a temperature transmitter uses the signed range. Read one as the other and everything looks fine until the value passes 32767. For an unsigned counter, that day always comes.
Thirty-two bits do not fit. A DINT, a REAL and a 32-bit counter need two registers. The protocol was written in 1979, for machines that had no such numbers. It says nothing about which half comes first.
Every manufacturer made a choice, and they did not all make the same one. Some put the high half first. Many gateways, drives and cheap devices put the low half first. On site this is called "word-swapped", as if it were a defect. In fact both choices are equally arbitrary.
On the two platforms, the order usually comes out of the program:
- A Siemens controller stores numbers high byte first. When you publish a data block with MB_SERVER, a DINT usually comes out high word first.
- A Rockwell controller stores numbers low byte first. When you copy a DINT into two INTs with COP, the low word lands in the first INT.
So the map is shaped by the program that builds it. Do not guess the order. Check it.
Getting this wrong is the most dangerous mistake in this chapter, because it does not look like a mistake. 220144 becomes 1542455299. 123.4 becomes whatever the bits happen to spell: perhaps 1.7 × 10⁻³⁸, perhaps 4.6 × 10²⁴. It is not zero, and it is not an error. If nobody watches the value closely, it can sit in a report for a year.
The only defence is to compare a value you know. Read the order number off the office screen, then read it off your own tag. If they match, the map is right. If they do not, you have learned in thirty seconds what a week of thinking would not have told you.
Where scaling belongs. Not in the driver. The driver's job is to bring the raw registers the device publishes. Turning 4863 into 48.63 °C is the job of a rung in your program. There everybody can see it. It was the same for the analog card in Chapter 5. A scaling factor buried in a communications setting is a number nobody will ever find again.
Setting a driver up
The driver in this app has seven fields. None of them is decoration. Each one answers something in the device's manual. On a real site you make the same decisions, only in other places:
- On Siemens the connection data sit in the MB_CLIENT block's parameters and its instance DB. Your program decides when a request goes out: you trigger MB_CLIENT's REQ input yourself.
- On Rockwell the same settings sit in the sample AOI's parameters, or in the gateway module's own configuration tool.
Address and port. Where the device lives. Port 502, unless somebody changed it. An address with no device behind it does not fail at once. The driver waits the whole timeout before it decides. So a typo in the last part of the address looks like a slow link.
Unit id. A device directly on Ethernet ignores this field. Behind a gateway it is essential. It selects which serial device answers. This is the sneakiest trap in the chapter. A wrong unit id works for years with a device that ignores it. Then one morning the device is replaced by another one behind a gateway, and the link stops.
Poll interval. How long to wait between rounds. "As fast as possible" is not the right answer. Every round makes work for the far end. Cheap devices, which run Modbus on the same processor as the measurement, answer exception 6 (slave device busy) when they are hurried.
Gap between requests. How long to wait between two requests inside a round. Usually zero. Not zero for the cheap device above. People often cannot find this field. If a round sends five requests back to back, a longer poll interval changes nothing.
Timeout. How long to wait before deciding no answer is coming. It must be longer than the device's worst time, not its usual time. On a device with a database behind it, the two can differ by a factor of ten.
Retries. How many more times to ask before declaring the link down. This is the arithmetic that matters:
worst time to notice = poll interval + (retries + 1) × timeout
A one-second timeout with three retries means the machine runs for four seconds on numbers that are no longer true. Riding out a short blip and noticing a failure quickly are the same dial. What you gain on one, you lose on the other. A work order that says "the line must stop within three seconds" is really asking about this line of arithmetic.
Blocking. One request for twenty registers, or twenty separate requests. The data is the same; the cost is not. Every request has a header and a round trip. On fussy devices a compulsory pause follows it as well. Lay out your receiving tags in the same order as the device's map. Then a whole page of its manual fits into one transfer.
The limits differ by direction. One request can read up to 125 registers, but write only up to 123. A write request has to carry the data as well as the header.
When no answer comes
This is the most important thing to know about a link that drops:
Nothing in your tags changes.
The last value that arrived stays there. It has the right type, it is in range, and it looks like a fresh reading. It goes on looking like one until somebody restarts something. A program that decides to reject a pack by looking at a weight goes on rejecting, or not rejecting, on a number from before lunch. And it does so without the slightest doubt.
This is not the fault of one particular driver. Most drivers behave this way. Zeroing the tag would not be better. A weight of zero is also a plausible number, and it also makes something happen.
So the status is not optional. A driver tells you two things, and both need to be written to a tag:
- health bit: TRUE while the last poll round completed;
- status code: why it did not.
These tags are not only for the diagnostics page. They go in series on every rung that acts on a remote number. A remote value and its health bit are one fact written into two tags. Using only one of them is a bug waiting for a bad day.
The codes. The low-numbered codes are the protocol's own exception codes. The device itself sends them. They mean the same on every Modbus device:
| code | the device is saying |
|---|---|
| 1 | I do not have that function. For example, you tried to write an input register. |
| 2 | I do not have that address, or not that many registers from it. |
| 3 | I do not accept that quantity. |
| 4 | Something broke inside me while answering. |
| 6 | You asked again before I had finished the last one. |
| 11 | Nobody behind the gateway answers to that unit id. |
The codes in the hundreds belong to the driver in this app. The protocol has no code for "there is no cable", because without a cable there is no protocol. Every driver gives these cases its own numbers:
| code | this driver is saying |
|---|---|
| 100 | Nothing is listening at that address and port. |
| 101 | Something is listening, but it did not answer in time. |
| 102 | A transfer points at a tag this project does not have. |
On real platforms the numbers differ, but the meanings are the same. On Siemens, MB_CLIENT reports them on its STATUS output. On Rockwell, the sample AOI or the gateway module reports them in its own status tags. Read which number means what in that instruction's or module's documents.
The rule that comes out of all this. When the link drops, the machine goes to a safe state by itself. When the link returns, it does not start again by itself. Restarting is a person's decision. This is the same principle as IEC 60204-1 §7.5: when power returns after an interruption, the machine does not start on its own. The reason is the same too. The machine cannot know what happened while it could not see.
Two controllers shake hands
Reading a temperature off a transmitter is one job. Asking another machine to do something is another. The difference is this: a request is an event, while a register holds a level.
Over a polled link these two are not the same thing. Pallets go missing in the gap between them.
Say you write 1 into a register to mean "send me a pallet". The other controller sees the 1 and sends a pallet. On the next round it sees 1 again. You did not change it, because from your side you asked once. Should it send another pallet? If it looks at the level, it does, and it keeps on doing so. If it looks for a change (an edge), it never sends a second pallet. From its side, the register never went back to 0.
The four-step handshake is the answer. The steps are the same whether the link is Modbus, PROFINET or two relay contacts between two panels.
- You set the REQUEST bit.
- It does the job and sets the ACK bit.
- You see ACK and clear REQUEST.
- It sees REQUEST gone and clears ACK.
Neither side moves until it has seen the other one move. That is why the pattern is robust. How often each side is polled does not matter. One may be much slower than the other. A round may be missed completely. The price is that each step can take up to one poll interval. Over a 200 ms link a handshake takes nearly a second. That is the price of being sure, and it is cheap.
What if the link drops halfway? Nothing bad happens. Both sides wait for each other in a defined step. When the cable goes back in, they carry on from where they were. This is the real reason to write it this way rather than with a timer: a handshake has no state that exists only in transit.
This pattern does not depend on the platform. On Siemens and on Rockwell alike, you write the steps with an INT and compares. Only the communication instruction differs.
Remote counters. The far end's totals are not yours. You cannot reset them. They were not zero when you arrived. They kept counting through your power cut. So do not try to own them. Take a baseline when the job starts and subtract:
made_on_this_order = their_total − their_total_when_we_started
This is correct after a power cut. It is correct if the far end restarts without telling you. It is correct if somebody replaces the device. The first order after such an event comes out wrong once; every order after that is right.