26 min read · Automation

The HMI shows a communication error even though the PLC power light is normal. In another case the screen shows no error, but the temperature reads 8.6 billion, or values are right some of the time and wrong the rest. These three symptoms sound like the same thing: no communication. But the causes sit in different layers, and if we try several fixes at once, we never learn which one actually worked.
This article works from the lowest layer upward, in order. Each layer asks one question that evidence can answer. It comes with a TypeScript script that Node 24 runs directly against a simulated PLC, where we inject one fault at a time. Nothing to install, no hardware needed. A manager can read the tables and explanations and follow along, and an engineer can run the code. The parts a script cannot do for you (wiring, duplicate IPs, termination) are collected in a manual checklist at the end.
The real problem: one symptom, causes in different layers
Here are three hypothetical scenarios. They are not BT San customer projects.
- A factory moves a press to another line. The technician changes the PLC IP to match the new network diagram, and the HMI immediately shows a communication error. The team spends half a day fixing register addresses, when the real problem is that the HMI still points to the old IP. The lowest layer had not even passed yet.
- A new HMI replaces the old one. It reads the PLC and shows no error, but the flow rate stored as float32 shows a strange number, because the new HMI model sets a different word order from the old one. Everything else is correct.
- A SCADA system reads dozens of devices through an RS-485 gateway and shows timeouts at intervals during the night shift, not all the time. The cause may be replies that take longer than the configured timeout, or replies that are truly lost to noise. These two can only be told apart by measuring.
The approach in this article has three rules. First, record the current state before touching anything (the settings sheet at the end of the article). Second, check from the bottom up. If a lower layer fails, do not fix the layers above it. Third, change one value at a time, then run the check again.
What Modbus says: what the documents confirm, and what we must not assume
The example uses Modbus TCP because its documents are free to open and it runs on a single machine. This table summarizes only what has been checked against the documents, and how each point affects troubleshooting.
| Topic | What the document says | Effect on troubleshooting |
|---|---|---|
| Address numbering | The Modbus Application Protocol V1.1b3 states that in the PDU, register addresses count from zero, so registers numbered 1-16 are sent as addresses 0-15 | The number in the manual (counting from 1, or with a 40001 prefix) and the number on the wire can differ. You need to know whether the HMI converts it. This is the source of off-by-one errors. |
| Registers per request | A Read Holding Registers (FC03) request specifies a quantity of 1 to 125 (0x7D) according to the spec | The spec gives a maximum ceiling. A real device may accept fewer. Check the manual for that model. |
| Exception | If a request is invalid, the responder sends the original function code plus 0x80, followed by an exception code, for example 01 ILLEGAL FUNCTION, 02 ILLEGAL DATA ADDRESS, 03 ILLEGAL DATA VALUE, 06 SERVER DEVICE BUSY, 0A GATEWAY PATH UNAVAILABLE, 0B GATEWAY TARGET DEVICE FAILED TO RESPOND | Receiving an exception means the device speaks Modbus and did answer. The problem is in the content of the request, not the cable or IP. |
| Unit Identifier | The Messaging on TCP/IP Implementation Guide V1.0b states that the unit id is used for routing within the system, typically to reach slaves on a serial line through a gateway. The client side sets it, and the server side must return the same value | If the unit id does not match, some devices stay silent and some reply. Scan to find out. Do not guess either way. |
| Port | The Implementation Guide specifies TCP port 502 as the registered Modbus port, and a server must have a listening socket on this port | Some devices let you change the port. Record the port actually configured in the settings sheet. |
| Vendor-specific addresses | The DELTA DVP Series PLC Communication Protocol document published by NOVUS states that D0 to D255 sit at Modbus addresses 1000 to 10FF (hexadecimal), and its example writes D1000 at 13E8 (hexadecimal), which is 0x1000 plus 1000 | Registers that a vendor names itself are converted to Modbus addresses by that vendor's formula. The formula differs by model and by vendor. |
| Float word order | The pymodbus documentation states that its register conversion functions have a word_order parameter, big or little, with big as the default | Even the library makes you choose. That means the spec does not force one order. Check the device manual or measure against a reference value. |
The example in this article does not simulate any particular brand of device. The register map, the reference values 0xA55A and 1234.5, and all response times are made-up values that we set ourselves. When you apply this, use the reference values given in the manual or by the installer of the actual device.
Overview of the example
A technician's real check is a six-step checklist. We wrote it to run from the bottom up and to stop immediately when a lower layer fails. This example does not go into RTU framing and CRC, which are already covered in the article Modbus RTU TCP RS-485 and Ethernet, linked at the end of this article. Here the focus is diagnosis.
| File | Role |
|---|---|
| modbus.ts | Builds and parses FC03 and FC06 frames, the exception name table, and float32 conversion in all four orders |
| client.ts | A small TCP client that matches replies by transaction id and returns null on timeout |
| plc-sim.ts | A simulated PLC on 127.0.0.1 with a random port, where faults can be injected one at a time |
| rules.ts | Pure logic with no sockets: finding the address offset, matching the float order, percentile, and the diagnosis rules |
| checks.ts | The six-step checklist, read-only (FC03) |
| demo.ts | Runs the checklist against eight simulated PLC variants and compares the results with what is expected |
| diagnose.test.ts | Tests using node:test |
| Step | Question asked | If it fails, it means |
|---|---|---|
| 1 | Can a TCP connection be opened to the IP and port? | Modbus has not even been reached: IP, subnet, port, firewall, cable |
| 2 | Does the configured unit id answer? If silent, which unit answers? | The unit id is wrong, or nothing speaks Modbus at all |
| 3 | Is the reference constant at the address the manual gives? Or how far is it shifted? | The address base is wrong (counting from 0 or 1) |
| 4 | In which word/byte order does the reference float decode correctly? | The word order is wrong, or the data type is not float32 |
| 5 | How does the response time compare with the HMI timeout and retry? Are any replies lost? | Replies are slower than the timeout, or the network/device loses replies |
| 6 | What reply or exception comes back for the block the HMI actually requests? | The address range or block size exceeds what the device accepts |
The simulated PLC: inject one fault at a time
The simulated PLC has a small register map. Address 100 holds the reference constant (which a commissioning sheet usually provides), addresses 102-103 hold the float 1234.5, and the remaining addresses up to 115 hold sequential numbers so that there is a range to read as a block. Each fault is just a field in a profile.
export const REF = { diagAddr: 100, diagValue: 0xa55a, floatAddr: 102, floatValue: 1234.5 };
export type Profile = {
unit: number; // the only unit id that answers (others are silent)
shift: number; // whole map moved by this many addresses (off-by-one fault)
floatOrder: FloatOrder;
delayMs: number; // reply delay (slow scan)
dropRate: number; // 0..1 chance a reply is silently dropped
maxQty: number; // largest block FC03 accepts
};
export const GOOD: Profile = { unit: 1, shift: 0, floatOrder: "ABCD", delayMs: 0, dropRate: 0, maxQty: 125 };Two points make the simulation match real devices. First, a mismatched unit id makes the simulated PLC stay silent instead of replying with an exception, because many real devices, and gateways that cannot find a slave, also stay silent. (The document has exception 0B for gateways to use, but not every gateway sends it.) Second, the random dropping of replies uses a fixed seed, so every run gives the same result and the results in this article can be checked again.
export function startPlc(over: Partial<Profile> = {}): Promise<{ port: number; close: () => Promise<void> }> {
const p = { ...GOOD, ...over };
const regs = registers(p);
const rand = mulberry32(7); // fixed seed: the same "random" drops on every run
const sockets = new Set<net.Socket>();
const server = net.createServer((sock) => {
sockets.add(sock);
sock.on("close", () => sockets.delete(sock));
sock.on("error", () => {});
let buf: Buffer = Buffer.alloc(0);
sock.on("data", (d) => {
const s = splitFrames(Buffer.concat([buf, d]));
buf = s.rest;
for (const f of s.frames) {
if (f[6] !== p.unit || rand() < p.dropRate) continue; // silence, like a real dead slave
const pdu = pduFor(p, regs, f);
const head = Buffer.alloc(7);
f.copy(head, 0, 0, 7);
head.writeUInt16BE(pdu.length + 1, 4);
setTimeout(() => sock.writable && sock.write(Buffer.concat([head, pdu])), p.delayMs);
}Steps 1 and 2: does TCP connect, and does the unit id answer?
Step 1 opens a TCP connection. If you get ECONNREFUSED, the target machine did answer but nothing is listening on this port (wrong port, or the service is off). If it simply times out, it is usually the IP, subnet, firewall or cable keeping packets from arriving. Telling these two symptoms apart gives you a direction from the first step. If this step fails, the script stops at once and does not go on to try register addresses.
Step 2 asks with the unit id configured in the HMI. If it answers (even with an exception), it passes. If it is silent, ask three times before concluding, because a single lost reply should not be read as a wrong unit. Then scan units 1 to 10 with a short timeout. If another unit answers, use that one in the following steps. If nobody answers at all, suspect that this port does not really speak Modbus TCP (for example, it is RTU over TCP), or that the gateway cannot find the target device.
async function read(c: Client, unit: number, addr: number, qty: number, timeout = 800) {
for (let i = 0; i < 3; i++) {
const { reply } = await c.ask(unit, 3, addr, qty, timeout);
if (reply) return reply;
}
return null;
} // 2. does the configured unit id answer at all? (an exception reply still counts as an answer)
let unit = h.unit;
const first = await read(c, unit, h.docAddr, 1);
f.unit = { configured: h.unit, answered: first !== null, sweep: [] };
if (first) say(`2 unit ${unit}: ตอบ`);
else {
say(`2 unit ${unit}: เงียบ สแกน unit 1-10`);
for (let u = 1; u <= 10; u++) if (u !== h.unit && (await c.ask(u, 3, h.docAddr, 1, 250)).reply) f.unit.sweep.push(u);
say(` unit ที่ตอบ: ${f.unit.sweep.join(", ") || "ไม่มี"}`);
if (!f.unit.sweep.length) return f;
unit = f.unit.sweep[0];
}Step 3: does the reference constant show whether the address is shifted?
The off-by-one error is one of the most common problems, because the number in the manual and the number on the wire can differ, as the table above explains. You do not need to guess. Ask the installer for a reference constant (a register known to hold a particular number), then read the address from the manual and its neighbors, plus and minus two. Wherever the constant shows up tells you the offset. The function that finds the answer is pure logic, so it can be tested without a socket.
// probes = [offset from the documented address, value read there]. null = no value (exception or silence).
// Returns how far the constant sits from where the manual says it is; the smallest distance wins.
export function findOffset(probes: [number, number | null][], constant: number): number | null {
const hits = probes.filter(([, v]) => v === constant).map(([d]) => d);
return hits.length ? hits.sort((a, b) => Math.abs(a) - Math.abs(b))[0] : null;
}
// Which of the four layouts turn these two registers into the known constant?
export function matchFloatOrders(words: number[], expected: number): FloatOrder[] {
return FLOAT_ORDERS.filter((o) => Math.abs(wordsToFloat(words, o) - expected) < 1e-3);
}
// Nearest-rank percentile of a list of response times.
export function percentile(xs: number[], p: number): number {
if (!xs.length) return 0;
const s = [...xs].sort((a, b) => a - b);
return s[Math.min(s.length - 1, Math.ceil((p / 100) * s.length) - 1)];
}
The result of this step gives the direction and size. For example, a value at distance +1 means the HMI must read one address higher than the calculated one. This can usually be fixed with the driver's address base option (counting from 0 or 1, and whether to strip the 40001 prefix). Do not fix it in the PLC program, because the addresses in the program are already correct. If the constant is not found at all, the manual may be for the wrong model, or the register may be in a different block (coil, input, holding).
Step 4: four float orders, pick the one that matches the reference value
A float32 takes two registers. ABCD means bytes from most to least significant, CDAB means the two words are swapped, BADC means the bytes within each word are swapped, and DCBA means everything is reversed. 1234.5 is 0x449A5000. The wire carries it as 449A 5000 (ABCD) or 5000 449A (CDAB). Decode the value in all four orders and pick the one that matches the reference value. This gives an answer, and there is no need to argue about what a given HMI brand calls its order.
// 32-bit float over two registers. Letters name the bytes of the big-endian float (A = most significant).
// The string says which float byte travels in wire position 0..3.
export const FLOAT_ORDERS = ["ABCD", "CDAB", "BADC", "DCBA"] as const;
export type FloatOrder = (typeof FLOAT_ORDERS)[number];
export function floatToWords(value: number, order: FloatOrder): [number, number] {
const be = Buffer.alloc(4);
be.writeFloatBE(value);
const wire = Buffer.from([...order].map((c) => be["ABCD".indexOf(c)]));
return [wire.readUInt16BE(0), wire.readUInt16BE(2)];
}
export function wordsToFloat(words: number[], order: FloatOrder): number {
const wire = Buffer.alloc(4);
wire.writeUInt16BE(words[0], 0);
wire.writeUInt16BE(words[1], 2);
const be = Buffer.alloc(4);
[...order].forEach((c, i) => (be["ABCD".indexOf(c)] = wire[i]));
return be.readFloatBE(0);
}If the reference value is symmetric, for example 0.0, all four orders give the same result, so it tells you nothing. The script reports this case as ambiguous. Choose a reference value whose four bytes are all different.
Step 5: measure response time against the HMI timeout and retry
Communication that works in a test tool can still fail on the HMI if the HMI timeout is shorter than the time the PLC actually takes to reply. So we measure the response time eight times and compare p95 and the maximum against the HMI timeout. A separate matter is replies that never arrive. Slow replies and lost replies need different fixes. Slow replies are fixed with the timeout and the polling load. Lost replies are fixed at the physical layer or in the PLC's load.
// 5. response time against the HMI's own timeout; lost = no reply within 3x that timeout
const ms: number[] = [];
let lost = 0;
for (let i = 0; i < 8; i++) {
const r = await c.ask(unit, 3, at, 1, h.timeoutMs * 3);
if (r.reply) ms.push(r.ms);
else lost++;
}
f.timing = { sent: 8, lost, p95: percentile(ms, 95), max: Math.max(0, ...ms), timeoutMs: h.timeoutMs, retries: h.retries };
say(`5 เวลาตอบ 8 ครั้ง: หาย ${lost}, p95 ${Math.round(f.timing.p95)} ms, สูงสุด ${Math.round(f.timing.max)} ms (timeout HMI ${h.timeoutMs} ms, retry ${h.retries})`);Once you know the reply loss rate, you can estimate what percentage of poll cycles the HMI will fail, given the number of retries. If 50% of replies are lost and there is 1 retry, a poll cycle fails completely about 0.5 squared, which is 25%. This assumes each attempt is independent, which is a rough approximation. Losses from noise tend to come in clusters and are not independent. So use this number to compare the size of the problem, not as a statistic to quote.
Step 6: read the block the HMI actually requests, and decode the exception code
Often a device answers everything normally except the block the HMI actually requests, which is large or spans a range with no registers. So the last step reads with the same quantity the HMI uses, then decodes the exception. Getting 02 means the range includes addresses that do not exist. Getting 03 means the requested quantity exceeds what the device accepts. Getting 01 means that function code is not supported. 0A and 0B usually come from a gateway, not from the PLC itself.
The diagnosis rules combine the results of every step into a list of causes, ordered from the lowest layer to the highest, with the fix in one sentence.
export function diagnose(f: Findings): Issue[] {
const out: Issue[] = [];
if (!f.tcp.ok) {
out.push({
code: "tcp",
says: `เปิด TCP ไม่ได้ (${f.tcp.error}) ยังไม่ถึงชั้น Modbus`,
fix: "ตรวจ IP, subnet, พอร์ต (ปกติ 502 แต่ตั้งเปลี่ยนได้), ไฟร์วอลล์, สาย/สวิตช์ และ IP ซ้ำ ด้วย ping และ arp ก่อนแตะการตั้งค่า HMI",
});
return out;
}
if (f.unit && !f.unit.answered) {
if (!f.unit.sweep.length) {
out.push({
code: "no-modbus-reply",
says: "TCP ต่อติดแต่ไม่มี unit id ไหนตอบเลย",
fix: "ตรวจว่าพอร์ตนี้พูด Modbus TCP จริง (ไม่ใช่ RTU over TCP หรือโปรโตคอลอื่น), เปิดใช้ Modbus server ในอุปกรณ์แล้ว และถ้ามี gateway ให้ดูฝั่งอนุกรม (baud, parity, สาย, termination)",
});
return out;
}
out.push({
code: "wrong-unit",
says: `unit id ${f.unit.configured} เงียบ แต่ unit ${f.unit.sweep.join(", ")} ตอบ`,
fix: `เปลี่ยน unit/slave id ใน HMI เป็น ${f.unit.sweep[0]} (หรือเปลี่ยนที่อุปกรณ์ แล้วจดลงใบตั้งค่า)`,
});
}Real run: eight profiles, diagnosis correct in every case
The demo starts the simulated PLCs one at a time on localhost with a random port, runs the checklist, prints the result, and compares it with the expected cause. The results below come from a real run on 2026-11-21. The ports and response times are the numbers from that run. Other runs will differ slightly.
=== A ปกติ (ไม่มีความผิดปกติ) ===
1 TCP: ต่อ 127.0.0.1:41195 ได้
2 unit 1: ตอบ
3 ค่าอ้างอิง 0xa55a: พบที่ที่อยู่ 100 (ห่าง 0)
4 float 1234.5: ABCD=1234.500 CDAB=8.607918e+9 BADC=-4.053210e-23 DCBA=7.402180e-39 -> ตรง: ABCD
5 เวลาตอบ 8 ครั้ง: หาย 0, p95 1 ms, สูงสุด 1 ms (timeout HMI 300 ms, retry 1)
6 บล็อกของ HMI (12 register): ตอบปกติ
=> [ok] ทุกชั้นผ่าน
แก้: ถ้า HMI ยังผิด ให้เทียบการตั้งค่าใน HMI กับใบตั้งค่าทีละช่อง
=== B พอร์ตผิด/ปิด ===
1 TCP: ต่อไม่ได้ ECONNREFUSED
=> [tcp] เปิด TCP ไม่ได้ (ECONNREFUSED) ยังไม่ถึงชั้น Modbus
แก้: ตรวจ IP, subnet, พอร์ต (ปกติ 502 แต่ตั้งเปลี่ยนได้), ไฟร์วอลล์, สาย/สวิตช์ และ IP ซ้ำ ด้วย ping และ arp ก่อนแตะการตั้งค่า HMI
=== C unit id ผิด (PLC ตอบ unit 5, HMI ตั้ง 1) ===
1 TCP: ต่อ 127.0.0.1:44445 ได้
2 unit 1: เงียบ สแกน unit 1-10
unit ที่ตอบ: 5
3 ค่าอ้างอิง 0xa55a: พบที่ที่อยู่ 100 (ห่าง 0)
4 float 1234.5: ABCD=1234.500 CDAB=8.607918e+9 BADC=-4.053210e-23 DCBA=7.402180e-39 -> ตรง: ABCD
5 เวลาตอบ 8 ครั้ง: หาย 0, p95 1 ms, สูงสุด 1 ms (timeout HMI 300 ms, retry 1)
6 บล็อกของ HMI (12 register): ตอบปกติ
=> [wrong-unit] unit id 1 เงียบ แต่ unit 5 ตอบ
แก้: เปลี่ยน unit/slave id ใน HMI เป็น 5 (หรือเปลี่ยนที่อุปกรณ์ แล้วจดลงใบตั้งค่า)
=== D ที่อยู่เลื่อน +1 ===
1 TCP: ต่อ 127.0.0.1:34759 ได้
2 unit 1: ตอบ
3 ค่าอ้างอิง 0xa55a: พบที่ที่อยู่ 101 (ห่าง 1)
4 float 1234.5: ABCD=1234.500 CDAB=8.607918e+9 BADC=-4.053210e-23 DCBA=7.402180e-39 -> ตรง: ABCD
5 เวลาตอบ 8 ครั้ง: หาย 0, p95 1 ms, สูงสุด 1 ms (timeout HMI 300 ms, retry 1)
6 บล็อกของ HMI (12 register): ตอบปกติ
=> [offset] ค่าอ้างอิงอยู่ห่างจากที่อยู่ที่คำนวณไว้ +1
แก้: ให้ HMI อ่านที่ +1 จากที่คำนวณเดิม มักแก้ได้ด้วยตัวเลือก address base (นับจาก 0 หรือ 1, ตัด 40001 ออกหรือไม่) อย่าแก้ที่ PLC
=== E float สลับ word (CDAB) ===
1 TCP: ต่อ 127.0.0.1:46301 ได้
2 unit 1: ตอบ
3 ค่าอ้างอิง 0xa55a: พบที่ที่อยู่ 100 (ห่าง 0)
4 float 1234.5: ABCD=8.607918e+9 CDAB=1234.500 BADC=7.402180e-39 DCBA=-4.053210e-23 -> ตรง: CDAB
5 เวลาตอบ 8 ครั้ง: หาย 0, p95 1 ms, สูงสุด 1 ms (timeout HMI 300 ms, retry 1)
6 บล็อกของ HMI (12 register): ตอบปกติ
=> [float-order] ถอดค่าอ้างอิงได้ถูกด้วยลำดับ CDAB ไม่ใช่ ABCD
แก้: ตั้ง word/byte order ของ tag ใน HMI เป็น CDAB (ใน HMI บางยี่ห้อเรียก swap words / byte swap)
=== F ตอบช้า 450 ms (timeout HMI 300 ms) ===
1 TCP: ต่อ 127.0.0.1:40395 ได้
2 unit 1: ตอบ
3 ค่าอ้างอิง 0xa55a: พบที่ที่อยู่ 100 (ห่าง 0)
4 float 1234.5: ABCD=1234.500 CDAB=8.607918e+9 BADC=-4.053210e-23 DCBA=7.402180e-39 -> ตรง: ABCD
5 เวลาตอบ 8 ครั้ง: หาย 0, p95 451 ms, สูงสุด 451 ms (timeout HMI 300 ms, retry 1)
6 บล็อกของ HMI (12 register): ตอบปกติ
=> [slow] คำตอบมาช้า p95 451 ms เกิน timeout ของ HMI 300 ms
แก้: เพิ่ม timeout ของ HMI ให้เกิน p95 พอสมควร (เช่น 2-3 เท่า) และลดภาระ: แบ่ง/ลดบล็อกที่ poll, เพิ่มรอบ poll, ดู scan time ของ PLC
=== G คำตอบหายแบบสุ่ม 35% ===
1 TCP: ต่อ 127.0.0.1:35627 ได้
2 unit 1: ตอบ
3 ค่าอ้างอิง 0xa55a: พบที่ที่อยู่ 100 (ห่าง 0)
4 float 1234.5: ABCD=1234.500 CDAB=8.607918e+9 BADC=-4.053210e-23 DCBA=7.402180e-39 -> ตรง: ABCD
5 เวลาตอบ 8 ครั้ง: หาย 4, p95 1 ms, สูงสุด 1 ms (timeout HMI 300 ms, retry 1)
6 บล็อกของ HMI (12 register): ตอบปกติ
=> [lossy] คำตอบหาย 4/8 ครั้ง (50%) ถ้า retry 1 ครั้ง โอกาสที่รอบ poll หนึ่งล้มทั้งชุดราว 25.0% (ประมาณจากสมมติว่าแต่ละครั้งเป็นอิสระต่อกัน)
แก้: ดูชั้นกายภาพ: สาย/ขั้วต่อ/สัญญาณรบกวน, CPU load ของ PLC, จำนวน client ที่ต่อพร้อมกัน, switch/ Wi-Fi และเก็บ capture ด้วย Wireshark ดูว่าคำขอหายหรือคำตอบหาย
=== H บล็อกใหญ่เกินที่อุปกรณ์รับ (สูงสุด 8, HMI ขอ 12) ===
1 TCP: ต่อ 127.0.0.1:45013 ได้
2 unit 1: ตอบ
3 ค่าอ้างอิง 0xa55a: พบที่ที่อยู่ 100 (ห่าง 0)
4 float 1234.5: ABCD=1234.500 CDAB=8.607918e+9 BADC=-4.053210e-23 DCBA=7.402180e-39 -> ตรง: ABCD
5 เวลาตอบ 8 ครั้ง: หาย 0, p95 1 ms, สูงสุด 1 ms (timeout HMI 300 ms, retry 1)
6 บล็อกของ HMI (12 register): exception 3 ILLEGAL DATA VALUE
=> [block-exception] อุปกรณ์ตอบ exception 3 (ILLEGAL DATA VALUE) กับบล็อกที่ HMI ใช้จริง
แก้: จำนวน register ต่อคำขอเกินที่อุปกรณ์รับได้ ลดขนาดบล็อกของ HMI (ดูค่าสูงสุดในคู่มือของรุ่นนั้น)
=== สรุป ===
A คาดว่า ok ได้ ok ตรง
B คาดว่า tcp ได้ tcp ตรง
C คาดว่า wrong-unit ได้ wrong-unit ตรง
D คาดว่า offset ได้ offset ตรง
E คาดว่า float-order ได้ float-order ตรง
F คาดว่า slow ได้ slow ตรง
G คาดว่า lossy ได้ lossy ตรง
H คาดว่า block-exception ได้ block-exception ตรง- Case A, normal: every step passes and no problem is concluded. This serves as a baseline showing that the checklist does not raise false alarms.
- Case B stops at step 1 with ECONNREFUSED and does not try the following steps, because reading registers has no meaning yet.
- Case C: unit 1 is silent, the scan finds unit 5, and the following steps continue with unit 5. This shows that the other registers are fine and there is only one problem.
- Case D: the reference value shows up at 101 instead of 100, so an offset of +1 is found. The following steps read with the offset compensated and then pass.
- Case E: of the four orders, only CDAB gives 1234.500. The other three give strange numbers, matching the symptom of a screen showing billions that opened this article.
- Case F: no replies are lost, but p95 is about 451 ms, above the HMI timeout of 300 ms. Everything is correct, but the HMI will report timeouts all the time.
- Case G: about half of the 8 replies are lost (random with a fixed seed, set to 35%, but a sample of eight need not come out at exactly 35%). The response time of the replies that do arrive is normal, so this is not a slowness problem.
- Case H: reading a block of 12 registers returns exception 03, because the simulated PLC accepts a maximum of 8 per request (a made-up value). The recommendation is to reduce the block size.
Test suite
diagnose.test.ts has seven cases. The first four test the pure logic that is easiest to get wrong: encoding then decoding back in all four orders; each order matching exactly one candidate while 0.0 is reported as ambiguous; finding the offset by choosing the nearest distance and returning null when nothing is found; and the nearest-rank percentile. The fifth case checks that each diagnosis rule gets its own code. The sixth checks the boundary (p95 exactly equal to the timeout is not flagged) and the 25.0% figure from the retry formula. The last case connects to a real socket on localhost and checks that a closed port and a shifted map are diagnosed from start to finish.
test("diagnose: a clean run is ok; each fault maps to its own code", () => {
assert.deepEqual(codes(ok), ["ok"]);
assert.deepEqual(codes({ tcp: { ok: false, error: "ECONNREFUSED" } }), ["tcp"]);
assert.deepEqual(codes({ ...ok, unit: { configured: 1, answered: false, sweep: [] } }), ["no-modbus-reply"]);
assert.deepEqual(codes({ ...ok, unit: { configured: 1, answered: false, sweep: [5] } }), ["wrong-unit"]);
assert.deepEqual(codes({ ...ok, offset: { delta: 1 } }), ["offset"]);
assert.deepEqual(codes({ ...ok, offset: { delta: null } }), ["address-not-found"]);
assert.deepEqual(codes({ ...ok, float: { orders: ["CDAB"] } }), ["float-order"]);
assert.deepEqual(codes({ ...ok, float: { orders: [] } }), ["float-nomatch"]);
assert.deepEqual(codes({ ...ok, timing: { ...ok.timing!, p95: 450 } }), ["slow"]);
assert.deepEqual(codes({ ...ok, timing: { ...ok.timing!, lost: 2 } }), ["lossy"]);
assert.deepEqual(codes({ ...ok, block: { silent: false, exception: 3 } }), ["block-exception"]);
});The physical layer a script cannot do for you: the manual checklist
The script starts at TCP, but many problems occur before that. Use this table as a checklist to inspect with your own eyes and real tools.
| Layer | What to check | How to check |
|---|---|---|
| IP and subnet | The PLC and HMI are in the same subnet, or there is a correct gateway, and no IP has a typo | Look at the settings page on both sides. Ping from a machine connected in the same subnet. |
| Duplicate IP | Two devices use the same IP. The symptom is a connection that comes and goes. | Check the ARP table from a PC (arp -a) and compare the MAC with the label on the device. Unplug the suspect device and see whether the IP still answers. |
| Cable and switch port | A broken cable, a loose connector, no link light, or a mismatch in speed/duplex | Check the link lights at both ends. Try replacing the cable and the port. |
| RS-485: wiring and termination | A/B polarity reversed, star wiring instead of daisy chain, no termination resistor at the end of the line, or too many | Check the wiring against the device manual. Use twisted pair and noise-shielded cable as the manufacturer recommends. |
| RS-485: baud, parity, stop bit | The settings on both sides must match. A mismatch usually shows up as silence or CRC errors. | Compare the values in the settings sheet with the actual settings page of every device on the same line. |
| Station / slave number | Station numbers are duplicated on the serial line, or do not match what the HMI is set to | Go through every station number and record them in a table. If you suspect a duplicate, connect one device at a time. |
| Firewall and VLAN | Port 502, or the port actually used, is blocked between networks | Test first from a machine on the same network as the PLC. If that passes, the problem is somewhere along the path. |
Serial-layer details such as RTU CRC and framing are in the article Modbus RTU TCP RS-485 and Ethernet, linked at the end of this article, and are not repeated here.
Applying it to real equipment
- Do not write values to a running PLC during testing. Always start with read-only functions (FC03 and FC04). The example script never sends FC06, and the simulated PLC accepts FC06 only to be complete with respect to the spec.
- Read only registers that the machine's maintainer confirms can be read, and avoid polling too often while the machine is in production. The load on a PLC that has to answer several clients is itself one cause of slow replies.
- Use Wireshark to capture while the problem occurs. The mbtcp filter shows the transaction id and unit id (mbtcp.trans_id, mbtcp.unit_id). You can see whether the request went out, whether the reply came back, how late it was, and which exception it was. That points to a lost request or a lost reply more accurately than guessing from the HMI screen.
- Register addresses differ by manufacturer and by model (the example in the table above is Delta DVP, where D0 is at hexadecimal 1000). Mitsubishi and Siemens also have their own formulas and rules. Use the manual for the model actually installed. We do not substitute numbers for brands we have not checked.
- Record a communication settings sheet (comms settings sheet) for every device: IP or station number, port, unit id, the starting address of each block, address base, float word order, timeout, retry, poll cycle, and the reference value used to confirm. Next time a problem occurs, you can compare right away.
- Record the state before every fix (screenshots of settings pages, values read) and change one value at a time. If you change two values at once and the problem goes away, you will not know which one fixed it, and next time you will not be able to repeat the fix.
Hypothetical examples: applying it to three businesses
A factory moves a machine to another line
Suppose a factory changes its IPs to a new diagram. The recorded settings sheet lets you see immediately that the HMI still points to the old IP. Step 1 of the checklist fails with a timeout, not ECONNREFUSED, which points to the IP or the route. There is no need to waste time on register addresses.
Changing the HMI model
Suppose a new HMI model is installed and float values are wrong. Run step 4 with the reference value the installer provides, and you get the correct order within seconds. Then set the new driver to match, and record the value in the settings sheet for next time.
SCADA reading several devices through an RS-485 gateway
Suppose there are timeouts at intervals. Run step 5 during the problem period and during a normal period, and compare p95 with the reply loss rate. If p95 is close to the timeout, fix it with the timeout and smaller blocks. If replies are lost in clusters while large machines are running, check the wiring and termination using the manual checklist.
All three are hypothetical scenarios to show how to use the checklist. They are not work for any BT San customer, and they are not results that actually happened.
Common mistakes and a checklist
- Skipping the lower layers and fixing register addresses when a TCP connection cannot even be opened
- Changing several values at once, then not knowing which one made the problem go away
- Concluding the unit id is wrong from a single lost reply. Ask again first.
- Believing that a passing ping means Modbus works. A passing ping proves only the IP level.
- Guessing the float word order from a name in the HMI menu instead of measuring it against a reference value
- Setting the HMI timeout equal to the average response time. Look at p95 and allow for retries.
- Testing by writing values to a PLC that is in use
- Not recording the settings, so you cannot compare with the last time
- Record the state before fixing: screenshots of settings pages, values read, and the time the symptom occurred
- Ask the installer for the settings sheet and the reference values (a constant register, and a reference float)
- Check IP, cable, port and link light by eye and by ping, following the manual checklist
- Open TCP to the real port. Separate ECONNREFUSED from a timeout.
- Ask with the configured unit id. If silent, ask again before scanning.
- Find the address offset using the reference constant
- Decode the float in all four orders and pick the one that matches
- Measure response time and reply loss rate against the timeout and retry
- Read the block the HMI actually uses and decode the exception
- Fix one value at a time, run the check again, and then update the settings sheet
Limitations: this example is learning material on made-up data. It is not production code and cannot communicate with real devices. The simulation has only one fault at a time. On site you often find several stacked together. A real device may reply with an exception in a case we simulate as silent (and the reverse). The poll cycle, response times and loss rates in this article are all made-up numbers. The Delta result comes from one DVP-series document that still needs to be checked against the manual for the model actually used. This article covers Modbus TCP only and does not go into other protocols such as Ethernet/IP, PROFINET or S7.
References
- Modbus Organization — MODBUS Application Protocol Specification V1.1b3 (0-based PDU addressing, FC03 quantity 1-125, exception codes) (accessed 2026-11-21)
- Modbus Organization — MODBUS Messaging on TCP/IP Implementation Guide V1.0b (MBAP, Unit Identifier, port 502) (accessed 2026-11-21)
- Modbus Organization — Specifications (index of the two PDFs above) (accessed 2026-11-21)
- pymodbus — Client documentation (word_order, timeout, retries) (accessed 2026-11-21)
- Wireshark — Modbus/TCP display filter reference (mbtcp.trans_id, mbtcp.unit_id) (accessed 2026-11-21)
- NOVUS-hosted DELTA DVP Series PLC Communication Protocol (D register to Modbus address example) (accessed 2026-11-21)
- Node.js v24 — net module (connection error and socket timeout behaviour) (accessed 2026-11-21)




