26 min read · Automation

A mixing tank can weigh up to three tonnes, yet the display jumps in unsteady half-kilogram steps. Or, in another case, a plant switches to a new weighing indicator and the weight on the HMI becomes eight hundred thousand kilograms. Both problems have the same root: the equipment was chosen by habit or brand, instead of by calculating how much resolution the load cell signal has left after it passes through the chosen path.
This article walks through the calculation step by step in TypeScript that Node 24 runs directly, with nothing to install and no hardware needed. It starts from the millivolt signal of the load cell, the fraction of rated capacity in use and the counts per kilogram. It then considers whether to send 4-20 mA into a PLC card or use a digital weighing indicator over RS485, and simulates a Modbus RTU read so you can see the real frames byte by byte, including a wrong CRC, an exception, and the two words of a 32-bit number arriving in swapped order.
The real problem: good equipment, but not enough resolution, or a reading that comes out wrong
A load cell signal is very small, only a few millivolts. It has to pass through an amplifier and an analog-to-digital converter (ADC), once or more, before it reaches the PLC. Every stage can lose resolution, and the lost resolution does not announce itself. The machine still produces a plausible-looking number; its steps are just coarser than the job needs.
Consider three hypothetical scenarios, not real BT San projects.
- A hypothetical animal feed plant has a mixing tank with three load points of 1,000 kg each. It uses a transmitter sending 4-20 mA into a 12-bit analog card and wants to read in 0.5 kg steps. But the display jumps in intervals, because one count of the card is about 0.73 kg.
- A hypothetical packaging plant replaces its weighing indicator with an RS485 model and reads the registers into a PLC. The weight shows up as a six-digit number, because the indicator sends the high word before the low word, the opposite of what the program expects.
- A hypothetical preparation room uses a 1,000 kg load cell for items that weigh no more than 20 kg. That uses only a few percent of the rated capacity. The signal over the real weight range is less than one millivolt, so there is no way to read in 10 g steps, however the card is changed.
All three cases can be checked in advance with a paper calculation, before buying and before running cable.
Facts from the documents used as the basis
| Topic | What the document says | Effect on the choice |
|---|---|---|
| Full-scale signal | The Mettler Toledo IND4x9 manual gives an example of a 2 mV/V load cell with a 100 kg rated capacity and a cell excitation voltage of 8.2 V. At 60 kg the signal is 2 x 8.2 x 60/100 = 9.84 mV, and at 30 kg it is 4.92 mV. | Signal = mV/V x excitation voltage x weight/rated capacity, a direct proportion. |
| Indicator input range | In the same manual, the specification of the indicator's analog input gives a differential signal range of -1 mV to 25 mV and a cell resistance of at least 80 ohms. | Check that the signal at maximum weight does not exceed the input range. |
| Modbus RTU | Modbus over Serial Line: RTU frames are separated by a silent interval of at least 3.5 character times and end with a 16-bit CRC, sent low byte first, then high byte. | The CRC must be assembled in the correct byte order. |
| FC03 and exceptions | Modbus Application Protocol: Read Holding Registers can read 1 to 125 registers. An error response uses function code 0x83 followed by an exception code of 01 to 04, and data is sent big-endian. | A normal response must be told apart from an exception by the high bit of the function code. |
| RS485 wiring | Modbus over Serial Line: up to 32 devices without a repeater, up to 1,000 m at 9600 baud with AWG26 or thicker cable. TI RS-485 Design Guide: the main line should have a terminating resistor at both ends, stubs should be as short as possible, and it cites 4,000 feet at 100 kbps. | Cable length is an advantage of RS485 over mV-level voltage signals. |
| Legal metrology | OIML lists R 76 (non-automatic weighing instruments) and R 60 (metrological requirements for load cells) as current international recommendations. | If the scale is used for trade, you must use equipment that is certified and verified under Thai law. |
This article is about engineering selection and calculation. It does not say that any design can be used for trade weighing. Weighing used for billing or trade requires a scale that is certified and verified under Thai weights and measures law. Users must confirm the requirements with the relevant authority themselves.
Topics outside the scope of this article that already have their own articles: the principles of Modbus RTU versus TCP, RS485 wiring and how to fix unreadable values are in the article on how Modbus RTU and TCP differ; the difference between 4-20 mA and 0-10 V is in the article on how 4-20 mA and 0-10 V differ; the split of duties between PLC and web app in recipe-based batching is in the article on recipe-based batching with a PLC and a web app; and reading a scale with a Delta PLC is in the article on Delta DVP-SE and AS in weighing work. This article focuses on what is still missing: calculating to choose the path, and decoding the frames so you can see them with your own eyes.
Overview of the example
The code is in the folder examples/load-cell-rs485-analog-selection/. It uses only Node 24 built-ins, with no npm install. TypeScript runs directly with the command node file.ts. (Node only strips the types and does not check them. It supports only syntax that can be erased, so enum and namespace are not used, and the .ts extension must be written in import statements, as the Node documentation requires.)
| File | Purpose |
|---|---|
| calc.ts | Signal calculator: signal, fraction of rated capacity, counts per kg, and the pass/fail conditions |
| modbus.ts | CRC-16, building the FC03 request, parsing the response, decoding the 32-bit number |
| simulator.ts | A digital weighing indicator simulated in memory |
| weight.ts | Reads the weight, adjusts the decimal point and sign, and rejects impossible values |
| data/cases.json, data/scenarios.json | 5 calculation cases and 9 read scenarios, including error cases |
| demo.ts / loadcell.test.ts | A script that runs every case, and a node:test suite of 6 tests |
Step 1: Calculate the signal and the fraction of rated capacity in use
The starting formula is: full-scale signal = sensitivity (mV/V) x excitation voltage (V). A 2 mV/V load cell at 5 V gives 10 mV at full rated capacity, and at other weights you multiply by the fraction, as in the Mettler Toledo example in the table above. When several cells are combined (through a junction box), the full-scale signal stays the same as for a single cell, but the total rated capacity becomes the number of cells times the rated capacity per cell. This example therefore uses total rated capacity = rated capacity per cell x number of cells, and assumes the weight is distributed evenly.
const totalCapacityKg = cells.capacityKg * cells.count;
// สัญญาณที่พิกัดเต็มของแต่ละเซลล์ = mV/V x แรงดันกระตุ้น (ตัวอย่างในคู่มือ Mettler Toledo ใช้สูตรเดียวกัน)
const fullScaleMv = cells.sensitivityMvV * cells.excitationV;
const maxGrossKg = load.deadKg + load.maxNetKg;
const mvAtMaxGross = (fullScaleMv * maxGrossKg) / totalCapacityKg;
// น้ำหนักที่แมปกับช่วงเต็มของตัวแปลง ADC
const spanKg =
path.spanKgMode === "capacity" ? totalCapacityKg : (totalCapacityKg * (path.adcSpanMv ?? 0)) / fullScaleMv;
const kgPerCount = spanKg / 2 ** path.adcBits;
const divisionsNeeded = load.maxNetKg / load.displayDivisionKg;
const countsPerDivision = load.displayDivisionKg / kgPerCount;
const noiseKg = path.noiseCountsPP * kgPerCount;- Maximum gross weight = the weight of the empty tank or dead load + the maximum material weighed. Only the material is what you actually weigh, but the cells must carry everything.
- The signal at maximum gross is the value the converter must be able to accept. If it exceeds the ADC input range, fix it at the indicator or lower the excitation voltage.
- The part that is actually useful is the signal of the net weight, which is a small fraction of the range. If the dead load is heavy and the rated capacity has a large margin, the usable weighing range becomes small.
- In the case of a cell that is too large for the job (case D in the example), only 3% of the rated capacity is used. The full-range signal of the weighed material is 0.25 mV. This small fraction is what the ADC has to divide into steps.
Step 2: How many kilograms is one count, and how does it compare with the step you need
An n-bit ADC divides its range into 2 to the power n steps. If that range is mapped to a total rated capacity of 3,000 kg (the case of a 4-20 mA transmitter scaled to full capacity, read over the full range by a 12-bit card), one count = 3000/4096 = 0.73 kg. That is already coarser than the required step of 0.5 kg, before considering noise.
const problems: string[] = [];
const usedPct = (maxGrossKg / totalCapacityKg) * 100;
// simplified: เกณฑ์ 20-80% เป็นกฎหยาบของตัวอย่างนี้ ของจริงดูพิกัดโหลดเกินปลอดภัยในแผ่นข้อมูลเซลล์
if (usedPct > 80) problems.push(`ใช้พิกัด ${usedPct.toFixed(0)}% เกิน 80% เหลือส่วนกันโหลดเกินน้อย`);
if (usedPct < 20) problems.push(`ใช้พิกัดเพียง ${usedPct.toFixed(0)}% ต่ำกว่า 20% สัญญาณช่วงน้ำหนักจริงเล็กเกินไป`);
if (path.spanKgMode === "adcSpanMv" && mvAtMaxGross > (path.adcSpanMv ?? 0))
problems.push("สัญญาณที่น้ำหนักสูงสุดเกินช่วงอินพุต ADC");
if (countsPerDivision < 1) problems.push(`หนึ่งขั้นแสดงผลมีไม่ถึง 1 count (${countsPerDivision.toFixed(2)})`);
// simplified: ใช้ noise peak-to-peak เป็นหน่วย count ที่ผู้ใช้กรอก ของจริงต้องวัดจากอุปกรณ์จริงที่น้ำหนักนิ่ง
if (countsPerDivision < path.noiseCountsPP)
problems.push(`noise ${path.noiseCountsPP} count (${noiseKg.toFixed(3)} กก.) ใหญ่กว่าหนึ่งขั้นแสดงผล ${load.displayDivisionKg} กก.`);The last two conditions are separate because they cause different damage. If counts per step is below 1, the displayed value skips numbers even though the load has not changed. If noise is larger than one step, the last digit flickers all the time even when the weight is steady. The noise figure in the example is a made-up value entered by the user. In real work you must measure it from the installed equipment, at a steady weight, over several hundred readings.
On e and n under OIML R 76: for certified weighing instruments, resolution is defined through the verification scale interval (e) and the number of intervals (n). The acceptable values depend on the class and the edition in force, which this article did not check against the full document. The criteria in the code (at least 1 count per step, and noise no larger than one step) are a rough rule for the example, not a legal criterion.
Step 3: Run all five cases, one fails, and how to fix it
{
"name": "A ถังผสม 3 จุดรับน้ำหนัก ต่อ transmitter 4-20 mA เข้าการ์ด PLC 12 บิต",
"cells": { "capacityKg": 1000, "count": 3, "sensitivityMvV": 2, "excitationV": 5 },
"load": { "deadKg": 800, "maxNetKg": 500, "displayDivisionKg": 0.5 },
"path": { "label": "analog 4-20 mA -> การ์ด 12 บิต", "adcBits": 12, "spanKgMode": "capacity", "noiseCountsPP": 2 }
},
{
"name": "A-แก้ ถังเดิม เปลี่ยนเป็นตัวชั่งดิจิทัล RS485 (ADC 24 บิต ช่วงอินพุต 20 mV)",
"cells": { "capacityKg": 1000, "count": 3, "sensitivityMvV": 2, "excitationV": 5 },
"load": { "deadKg": 800, "maxNetKg": 500, "displayDivisionKg": 0.5 },
"path": { "label": "ตัวชั่งดิจิทัล RS485", "adcBits": 24, "spanKgMode": "adcSpanMv", "adcSpanMv": 20, "noiseCountsPP": 64 }
},== ส่วนที่ 1: คำนวณทางส่งสัญญาณ (ตัวเลขสมมติ) ==
A ถังผสม 3 จุดรับน้ำหนัก ต่อ transmitter 4-20 mA เข้าการ์ด PLC 12 บิต
พิกัดรวม 3000 กก. | สัญญาณเต็มพิกัด 10 mV | ที่น้ำหนักสูงสุด 1300 กก. = 4.33 mV (ใช้พิกัด 43%)
analog 4-20 mA -> การ์ด 12 บิต: 0.73242 กก./count | ต้องการ 1000 ขั้น | 0.7 count/ขั้น | noise 1.465 กก.
ผล: ไม่ผ่าน
- หนึ่งขั้นแสดงผลมีไม่ถึง 1 count (0.68)
- noise 2 count (1.465 กก.) ใหญ่กว่าหนึ่งขั้นแสดงผล 0.5 กก.
A-แก้ ถังเดิม เปลี่ยนเป็นตัวชั่งดิจิทัล RS485 (ADC 24 บิต ช่วงอินพุต 20 mV)
พิกัดรวม 3000 กก. | สัญญาณเต็มพิกัด 10 mV | ที่น้ำหนักสูงสุด 1300 กก. = 4.33 mV (ใช้พิกัด 43%)
ตัวชั่งดิจิทัล RS485: 0.00036 กก./count | ต้องการ 1000 ขั้น | 1398.1 count/ขั้น | noise 0.023 กก.
ผล: ผ่าน
C ชั่งแท่นเดียว 500 กก. ต่อ analog การ์ด 16 บิต
พิกัดรวม 500 กก. | สัญญาณเต็มพิกัด 10 mV | ที่น้ำหนักสูงสุด 240 กก. = 4.80 mV (ใช้พิกัด 48%)
analog 4-20 mA -> การ์ด 16 บิต: 0.00763 กก./count | ต้องการ 1000 ขั้น | 26.2 count/ขั้น | noise 0.061 กก.
ผล: ผ่าน
D เลือกโหลดเซลล์ใหญ่เกินงาน 1000 กก. ชั่งของสูงสุด 20 กก.
พิกัดรวม 1000 กก. | สัญญาณเต็มพิกัด 10 mV | ที่น้ำหนักสูงสุด 25 กก. = 0.25 mV (ใช้พิกัด 3%)
analog 4-20 mA -> การ์ด 16 บิต: 0.01526 กก./count | ต้องการ 2000 ขั้น | 0.7 count/ขั้น | noise 0.122 กก.
ผล: ไม่ผ่าน
- ใช้พิกัดเพียง 3% ต่ำกว่า 20% สัญญาณช่วงน้ำหนักจริงเล็กเกินไป
- หนึ่งขั้นแสดงผลมีไม่ถึง 1 count (0.66)
- noise 8 count (0.122 กก.) ใหญ่กว่าหนึ่งขั้นแสดงผล 0.01 กก.Reading the results one item at a time.
- Case A: three load cells of 1,000 kg each, full-scale signal 10 mV, 43% of rated capacity in use, which is fine. The problem is the resolution of 0.73 kg per count against the required step of 0.5 kg, which gives only 0.7 count per step. Noise of 2 counts is 1.465 kg, three times larger than one step. The result is a fail on two conditions.
- A fix that does not change the load cells: switch to a digital weighing indicator that converts internally with a 24-bit ADC and a 20 mV input range, mapped to 6,000 kg (a signal of 4.33 mV at 1,300 kg is within this range). One count drops to 0.00036 kg and noise of 64 counts drops to 0.023 kg, giving 1,398 counts per step. It passes. The indicator sends the adjusted value out over RS485, so this resolution is not swallowed at the analog card.
- Other fixes that should also be compared: an analog card of 16 bits or more (case C uses 16 bits with a single cell and passes, while case A must be recalculated with the figures of that specific card), or lowering the required step if the job can accept it. Each path has a different price and different advantages. Calculate, then choose.
- Case C: a single 500 kg load cell, 48% of rated capacity in use, a 16-bit card, 26 counts per step of 0.2 kg. It passes with the simpler analog path. This is a case where analog is sufficient, and there is no need to buy a digital device.
- Case D: a cell that is too large for the job fails because only 3% of the rated capacity is used, and as a result counts per step is below one. Switching to a digital indicator helps somewhat, but the most direct fix is to choose a cell with a smaller rated capacity.
- Case E: a sensitivity of 0 is rejected with a RangeError and the calculation does not continue. Data that is divided by zero silently becomes infinity, so it must be stopped at the entry point.
A note on the criteria for choosing a path. The numbers above do not mean RS485 is always better than analog. What is better in case A is putting a high-resolution ADC close to the cell and sending out a number, which can be done with either an RS485 indicator or a transmitter that sends Modbus. But in case C, a straightforward analog connection is enough.
When to use analog and when to use an RS485 indicator
| Factor | Analog 4-20 mA / 0-10 V into a PLC card | Digital RS485 indicator (Modbus RTU) |
|---|---|---|
| Resolution | Limited by the card's bits and the total rated capacity (see case A) | The ADC is inside the indicator, which sends the adjusted value as a number |
| Calibration | Done at the transmitter and in the PLC program scale, so two places must be maintained | The calibration values are stored in the indicator, and the number the PLC reads is already in kilograms |
| Cable length and noise | A current signal resists interference better than voltage, but it is still a continuous signal | Sent as frames with a CRC as specified, and can run as long as Modbus specifies |
| Status and errors | Gives a single value. Faults can be seen only from current below 4 mA or out of range | Can read steady state, over-capacity and error codes, if that model has the registers |
| Update speed | Continuous, depending on the card's scan time and the filter | Depends on the PLC polling cycle and the indicator's update rate. Ask the manufacturer |
| Complexity | Easy to connect, no protocol | Requires setting baud, parity, address, word order, and reading the manual's register map |
The difference between current and voltage on the analog side and the details of RS485 wiring can be read in the related articles. The links are at the end of this article. Connecting a Delta PLC to a scale over Modbus is in the article on Delta DVP-SE and AS in weighing work.
Step 4: Build the Modbus RTU request and the CRC-16
An FC03 request frame consists of the slave address (1 byte), the function code 0x03, the start address (2 bytes), the number of registers (2 bytes), and the CRC (2 bytes). Multi-byte values are big-endian, except the CRC, which is sent low byte first. According to the documentation, the CRC is calculated over all the preceding bytes, starting from the value 0xFFFF and using the reflected polynomial 0xA001.
export function crc16(bytes: Uint8Array): number {
let crc = 0xffff;
for (const b of bytes) {
crc ^= b;
for (let i = 0; i < 8; i++) crc = crc & 1 ? (crc >> 1) ^ 0xa001 : crc >> 1;
}
return crc;
}
export function withCrc(body: number[]): Uint8Array {
const crc = crc16(Uint8Array.from(body));
return Uint8Array.from([...body, crc & 0xff, crc >> 8]); // ไบต์ต่ำก่อน ตามข้อกำหนด Modbus over Serial Line
}
export function buildReadHolding(slave: number, start: number, qty: number): Uint8Array {
if (qty < 1 || qty > 125) throw new RangeError("FC03 อ่านได้ 1-125 รีจิสเตอร์");
return withCrc([slave, 0x03, start >> 8, start & 0xff, qty >> 8, qty & 0xff]); // big-endian
}The reference values that must always match, to prove the CRC is correct, are these: the CRC of the message 123456789 must be 0x4B37 (the standard value of CRC-16/MODBUS from the general CRC catalogue, not taken from the Modbus documents checked in this article), and a request to read 2 registers from address 1 starting at 0 must be 01 03 00 00 00 02 C4 0B. The test suite checks both values.
test("CRC-16/Modbus ตรงกับค่ามาตรฐาน (check value ของ '123456789' คือ 0x4B37)", () => {
assert.equal(crc16(new TextEncoder().encode("123456789")), 0x4b37);
const f = buildReadHolding(1, 0, 2); // รู้จักกันดีว่า 01 03 00 00 00 02 C4 0B
assert.deepEqual([...f], [1, 3, 0, 0, 0, 2, 0xc4, 0x0b]);
});Step 5: Parse the response: normal, exception, and wrong CRC
The parser must check things in order: the minimum length first, then the CRC before trusting any of the content. Only then look at the address and at whether the function code is 0x83 (the exception for FC03). If it is a normal response, check that the byte count is even and matches the actual length, and only then assemble the registers two bytes at a time.
export function parseReadHolding(frame: Uint8Array, slave: number): Parsed {
if (frame.length < 5) return { ok: false, reason: "short", detail: `ยาว ${frame.length} ไบต์` };
const body = frame.subarray(0, frame.length - 2);
const got = frame[frame.length - 2] | (frame[frame.length - 1] << 8);
if (crc16(body) !== got) return { ok: false, reason: "crc", detail: `CRC ที่ได้ 0x${got.toString(16)} คำนวณได้ 0x${crc16(body).toString(16)}` };
if (frame[0] !== slave) return { ok: false, reason: "wrong_slave", detail: `ได้ address ${frame[0]}` };
if (frame[1] === 0x83) {
const code = frame[2];
return { ok: false, reason: "exception", detail: `exception ${code} ${EXCEPTIONS[code] ?? "ไม่รู้จัก"}` };
}
if (frame[1] !== 0x03 || frame[2] !== body.length - 3 || frame[2] % 2 !== 0)
return { ok: false, reason: "bad_length", detail: "byte count ไม่ตรงกับข้อมูล" };
const registers: number[] = [];
for (let i = 3; i < body.length; i += 2) registers.push((body[i] << 8) | body[i + 1]);
return { ok: true, registers };
}A real device says nothing at all when the request has a bad CRC or the wrong address. The simulator does the same (it returns null), so on our program's side it appears as a timeout. That is a different symptom from an exception, where the device replies that it refuses to do the request. Telling these two symptoms apart helps a great deal in diagnosis. A timeout is usually about the cable, the address or the baud rate. An exception means the cable works but the request does not match the register map.
export function respond(dev: Indicator, request: Uint8Array): Uint8Array | null {
if (request.length < 8 || crc16(request.subarray(0, 6)) !== (request[6] | (request[7] << 8))) return null; // CRC เสีย: อุปกรณ์จริงเงียบ
if (request[0] !== dev.slave) return null;
const fc = request[1];
const start = (request[2] << 8) | request[3];
const qty = (request[4] << 8) | request[5];
const exc = (code: number) => withCrc([dev.slave, fc | 0x80, code]);
if (fc !== 0x03) return exc(1);
if (qty < 1 || qty > 125) return exc(3);
const u = dev.raw >>> 0;
const hi = u >>> 16, lo = u & 0xffff;
const regs = [dev.order === "hi-lo" ? hi : lo, dev.order === "hi-lo" ? lo : hi, dev.decimals, (dev.stable ? 1 : 0) | (dev.overload ? 2 : 0)];
if (start + qty > regs.length) return exc(2);
const out: number[] = [dev.slave, 0x03, qty * 2];
for (const r of regs.slice(start, start + qty)) out.push(r >> 8, r & 0xff);
return withCrc(out);
}Step 6: A 32-bit number from two registers, word order, and sign
A Modbus register is 16 bits wide, so a 32-bit integer weight uses two registers. The Modbus specification defines the byte order inside a register as big-endian, but it does not define whether the high word must come first. Each manufacturer chooses for itself, so this must be read from the manual and tested with a known weight.
export function decodeInt32(regs: [number, number], order: WordOrder): number {
const [hi, lo] = order === "hi-lo" ? regs : [regs[1], regs[0]];
return ((hi << 16) | lo) | 0;
}Two points are often missed. The first is the sign: if you do not force a signed integer, a small negative value after zeroing (for example -0.52 kg) is read as a number around four billion. The second is the decimal point: the indicator sends an integer in the smaller unit, for example 1234 means 12.34 kg when the decimal-point register is 2, according to the example's made-up register map.
export function readWeight(send: Transport, slave: number, order: WordOrder, maxPlausibleKg: number): Reading {
const reply = send(buildReadHolding(slave, 0, 4));
if (!reply) return { ok: false, error: "timeout: ไม่มีคำตอบ (สายขาด address ผิด หรือ CRC ของคำขอเสีย)" };
const p = parseReadHolding(reply, slave);
if (!p.ok) return { ok: false, error: `${p.reason}: ${p.detail}` };
if (p.registers.length !== 4) return { ok: false, error: "ได้รีจิสเตอร์ไม่ครบ 4 ตัว" };
const raw = decodeInt32([p.registers[0], p.registers[1]], order);
const decimals = p.registers[2];
if (decimals > 3) return { ok: false, error: `ตำแหน่งจุดทศนิยม ${decimals} ผิดปกติ` };
const kg = raw / 10 ** decimals;
// กันลำดับคำผิด: ค่าที่ผิดมักใหญ่เกินพิกัดเครื่องชั่งหลายเท่า
if (Math.abs(kg) > maxPlausibleKg) return { ok: false, error: `ค่า ${kg} กก. เกินพิกัดที่เป็นไปได้ ${maxPlausibleKg} กก. ตรวจลำดับคำ (word order)` };
const status = p.registers[3];
return { ok: true, kg, stable: !!(status & 1), overload: !!(status & 2) };
}The line that compares against maxPlausibleKg is the safety net for word order. A wrong order gives a number hundreds of times too large almost every time. This value should come from the scale's rated capacity times a margin, not a number put in at random.
Running it: nine read scenarios
demo.ts sends requests to the simulated indicator one scenario at a time, from the scenarios.json file, which contains both normal cases and deliberately broken ones.
for (const s of load("data/scenarios.json")) {
const dev: Indicator = { slave: 1, order: s.deviceOrder, raw: s.raw, decimals: s.decimals, stable: s.stable, overload: s.overload };
const send = (r: Uint8Array) => {
const out = respond(dev, r);
if (out && s.flipByte !== undefined) out[s.flipByte] ^= 0x01;
return out;
};
console.log(`\n${s.name}`);
if (s.start !== undefined) {
const reply = respond(dev, buildReadHolding(1, s.start, s.qty))!;
const p = parseReadHolding(reply, 1);
console.log(` ตอบ: ${hex(reply)} -> ${p.ok ? "ok" : p.reason + " " + p.detail}`);
continue;
}
const slave = s.askSlave ?? 1;
const reply = send(buildReadHolding(slave, 0, 4));
if (reply) console.log(` ตอบ: ${hex(reply)}`);
const r = readWeight((q) => send(q), slave, s.readOrder, 1200);
console.log(r.ok ? ` อ่านได้ ${r.kg} กก. นิ่ง=${r.stable} เกินพิกัด=${r.overload}` : ` อ่านไม่ได้: ${r.error}`);
}== ส่วนที่ 2: อ่านน้ำหนักผ่าน Modbus RTU จำลอง ==
คำขอ FC03 slave 1 เริ่ม 0 จำนวน 4: 01 03 00 00 00 04 44 09
น้ำหนักปกติ 12.34 กก. นิ่ง
ตอบ: 01 03 08 00 00 04 d2 00 02 00 01 4c 41
อ่านได้ 12.34 กก. นิ่ง=true เกินพิกัด=false
ค่าติดลบ -0.52 กก. (ศูนย์เคลื่อนลง)
ตอบ: 01 03 08 ff ff ff cc 00 02 00 01 b1 c3
อ่านได้ -0.52 กก. นิ่ง=true เกินพิกัด=false
ลำดับคำผิด: อุปกรณ์ส่ง lo-hi แต่เราอ่านเป็น hi-lo
ตอบ: 01 03 08 04 d2 00 00 00 02 00 01 06 29
อ่านไม่ได้: ค่า 808714.24 กก. เกินพิกัดที่เป็นไปได้ 1200 กก. ตรวจลำดับคำ (word order)
ลำดับคำถูกต้อง lo-hi
ตอบ: 01 03 08 04 d2 00 00 00 02 00 01 06 29
อ่านได้ 12.34 กก. นิ่ง=true เกินพิกัด=false
ลำดับคำผิดกับค่าติดลบ
ตอบ: 01 03 08 ff cc ff ff 00 02 00 01 b6 c4
อ่านไม่ได้: ค่า -33423.37 กก. เกินพิกัดที่เป็นไปได้ 1200 กก. ตรวจลำดับคำ (word order)
ค่ากำลังแกว่ง ไม่นิ่ง และเกินพิกัด
ตอบ: 01 03 08 00 00 cb 84 00 02 00 02 55 b3
อ่านได้ 521 กก. นิ่ง=false เกินพิกัด=true
ขออ่านที่อยู่เกินแผนที่ (exception 02)
ตอบ: 01 83 02 c0 f1 -> exception exception 2 ILLEGAL DATA ADDRESS
สายถูกรบกวน: คำตอบถูกพลิก 1 บิต (CRC error)
ตอบ: 01 03 08 00 01 04 d2 00 02 00 01 4c 41
อ่านไม่ได้: crc: CRC ที่ได้ 0x414c คำนวณได้ 0x815c
address ผิด: อุปกรณ์ไม่ตอบ (timeout)
อ่านไม่ได้: timeout: ไม่มีคำตอบ (สายขาด address ผิด หรือ CRC ของคำขอเสีย)Reading the results one item at a time.
- The request 01 03 00 00 00 04 44 09 is slave 1 reading 4 registers starting at 0. The response is 01 03 08 00 00 04 d2 ... The byte 08 is the number of data bytes, 4 registers x 2, and 00 00 04 d2 is 1234, which with 2 decimal places gives 12.34 kg, stable.
- The negative value ff ff ff cc is -52, giving -0.52 kg. It is read correctly because it is forced to a signed number.
- Wrong word order: the indicator sends the low word first (04 d2 00 00) but we read it as high word first, which gives 80,871,424. Divided by two decimal places, that is 808,714.24 kg. The program rejects it because it exceeds 1,200 kg, and tells you to check the word order. The next line shows that reading with the correct lo-hi order gives 12.34 kg as before.
- Wrong word order with a negative value does not always give a huge number. It gives -33,423.37 kg, which is still caught because it is beyond the rated capacity. But if the real weight happens to make the swapped value fall within the plausible range, the swap will not be caught. So you must test with a known weight at installation and not rely on the range guard alone.
- A weight of 521.00 kg with status not stable and over capacity. The program returns the value with status flags. The caller must not use an unstable value to decide a dispense or to record a weight.
- Reading beyond the map (start at 2, count 8) gives 01 83 02 c0 f1, which is exception 02 ILLEGAL DATA ADDRESS. Note that function code 0x83 is 0x03 plus 0x80.
- A bit flipped on the line: one data byte changed from 00 to 01. The program computes a new CRC that does not match the one received, so it rejects the frame. It is not read as a wrong weight.
- Wrong address: the indicator does not respond. The result is a timeout.
Test suite
loadcell.test.ts has 6 cases and runs with node --test loadcell.test.ts, giving 6 passes. It covers the standard CRC value and the request; case A failing while the digital indicator passes; rejection of bad data; decoding the 32-bit value in both word orders and a negative value; a wrong word order that gets caught; and an exception, a bad CRC, a timeout and a short frame.
test("exception, CRC เสีย, timeout, และกรอบสั้น", () => {
const exc = respond(dev(), buildReadHolding(1, 2, 8))!;
assert.deepEqual(parseReadHolding(exc, 1), { ok: false, reason: "exception", detail: "exception 2 ILLEGAL DATA ADDRESS" });
const bad = respond(dev(), buildReadHolding(1, 0, 4))!;
bad[4] ^= 1;
const p = parseReadHolding(bad, 1);
assert.ok(!p.ok && p.reason === "crc");
assert.equal(respond(dev(), buildReadHolding(9, 0, 4)), null);
assert.equal(respond(dev(), withCrc([1, 3, 0, 0, 0])), null);
assert.ok(!parseReadHolding(Uint8Array.from([1, 3]), 1).ok);
});In real use: what the example does not do
- A real serial port: the example does not open a port. A real system must set the baud rate, parity and stop bits to match the device, wait for the 3.5-character silent interval between frames, and set a timeout and retries. If you use an existing library, check that it supports the word order of that model.
- Continuous reading: the example reads once per scenario. A real system needs a polling cycle, value filtering (an average, or waiting until stable), and handling for several timeouts in a row, such as whether to raise an alarm or stop the production line.
- Several indicators on one line: Modbus allows 32 devices without a repeater, but the total response time grows with the number of devices, so the real polling cycle must be calculated.
- Law and calibration: the calibration values are stored in the indicator. They require standard test weights, a date and an inspector. If you weigh for trade, you must use equipment that is certified and verified under Thai law.
- Electrical protection: grounding, shielding and terminating resistors follow the manufacturer's manual and the guidance from TI and Modbus. This example does not cover them.
Hypothetical examples: adapting it to three businesses
Animal feed mill
A large mixing tank has a heavy dead load and carries several tonnes. Check the fraction of rated capacity and the counts per step before choosing the card. If you need a finer step than the card gives, a digital indicator that sends Modbus can help, and the PLC still takes the value to control the recipe as before. See the article on recipe-based batching for the split of duties between PLC and web app.
Small packaging plant
For a single weighing platform where the load is well below the rated capacity, a 16-bit analog card is enough (like case C). It is economical and easy to wire. When there are several platforms, or you want stable and over-capacity status from the indicator, move to RS485 so you can read several indicators on one line.
Laboratory or preparation room
For light items and a fine step, such as reading 10 grams, choose a small-capacity load cell so that the calculated usage is over fifty percent of the actual working range, instead of using what you already have (case D). Work that must be certified must start from a scale that is certified as a complete set.
Common mistakes and a checklist
- Choosing a cell by the numbers in stock, without calculating the fraction of rated capacity actually used, including the tank weight.
- Forgetting that dead load eats into the signal, so the range left for weighing is smaller than expected.
- Looking only at the card's bit count, without calculating counts per kilogram from the mapped range.
- Not measuring noise at a steady weight before concluding that the step is fine enough.
- Reading a 32-bit register without confirming the word order with a known weight.
- Reading as an unsigned integer, so a negative value after zeroing becomes a huge number.
- Not checking the CRC, or not telling a timeout from an exception, so the troubleshooting goes the wrong way.
- Using a value that is not yet stable to decide a raw-material dispense or to record a weight.
- Assuming that weighing used inside the plant can be used for trade, without checking the legal requirements.
- Note the load cell model, sensitivity, excitation voltage, number of points and dead load.
- Calculate the signal at maximum weight and the fraction of rated capacity in use, and check that it does not exceed the input range.
- Set the display step you need, then calculate counts per step for each path.
- Measure the real noise at a steady weight and compare it with the step you need.
- If you choose RS485, confirm the register map, word order, decimal point and sign with a known test weight.
- Test abnormal cases: a disconnected cable, a wrong address and a bad CRC. Check that the system raises an alarm and stops safely.
- Record the zero value, the value at the test weight, the date and the inspector, and set a re-check interval.
Cautions about the example: the ADC noise figures, the load cells and the indicator's register map are all made up and do not match any model. There is no real serial port, no frame timing and no value filtering, and it was not designed for trade weighing. Use it as a learning model, not as code ready for real use.
References
- METTLER TOLEDO IND4x9: Installation information (ตัวอย่างคำนวณ mV/V x แรงดันจ่ายเซลล์ และช่วงอินพุต analog) (accessed 2026-11-21)
- Modbus over Serial Line Specification and Implementation Guide V1.02 (RTU, CRC, 32 อุปกรณ์, 1000 ม. ที่ 9600 baud) (accessed 2026-11-21)
- Modbus Application Protocol Specification (FC03, exception 0x83, big-endian) (accessed 2026-11-21)
- Texas Instruments: The RS-485 Design Guide (SLLA272) (ตัวต้านทานปลายสาย สายแยก 4000 ฟุตที่ 100 kbps) (accessed 2026-11-21)
- OIML: รายการข้อแนะนำสากล (R 76 เครื่องชั่งแบบไม่อัตโนมัติ, R 60 load cell) (accessed 2026-11-21)
- Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)




