IMD SolutionComputing LibraryShop main store

How-to

Modbus TCP data logging to a database from a plant PC

Edge computing and IIoT Published 7 min read

Short answer

Commission a Modbus TCP logger as two separately proven operations: one FC03 read of the target holding registers, then one parameterized test insert into the database. Join them on a one-minute timer guarded against overlapping cycles, decode 16-bit registers with the signedness your PLC map states, and keep the logger a read-only passenger outside control and safety.

On this page
  1. Commission one read before anything repeats
  2. Worked example: one FC03 read of registers 40108 to 40110
  3. Prove the insert on its own
  4. Run the one-minute cycle without overlap
  5. Keep the logger off the control path
  6. The commissioning order and the decision
  7. Questions asked

A Modbus TCP logger that writes one row per minute to a database works when you commission it as two separately proven operations: one read of the target holding registers with function code 3, and one test insert into the database. Join them only after both pass, on a timer guarded so a slow cycle can never overlap itself. Most first-day failures come from two things you can settle on the bench: the difference between a register's documented address and the protocol offset, and the signed or unsigned reading of a 16-bit register. Build the logger as a read-only passenger on the network: it never writes to the controller, and the machine must run with it switched off.

Commission one read before anything repeats #

Changing the polling rate, reconnecting repeatedly, or replacing the application with an HMI will not fix a wrong register address or a failed database connection. Settle both with one narrow test each, before any timer runs.

  1. Write down, for every value, the documented register reference, the data type (16-bit signed, 16-bit unsigned, or two-register 32-bit), and the units.
  2. Check which convention your Modbus TCP client library documents: the zero-based protocol offset or the five-digit 4xxxx reference. For holding registers the two differ by 40001.
  3. Point the client at the controller's address and TCP port 502, the standard Modbus TCP port unless the device documents another.
  4. Send one Read Holding Registers request, function code 3, outside any recurring task, and record where a failure happens: at connection, as a timeout, or as a Modbus exception code.
  5. Check the response shape: a valid answer reports a byte count of two bytes per requested register and carries that many data bytes.

A timeout points at reachability or endpoint availability; a Modbus exception points at the requested address range or an unsupported operation. A successful connection alone proves neither the register range nor the data. Proceed when one request returns the expected number of values, checked against values you set yourself in a simulator or a spare register.

Worked example: one FC03 read of registers 40108 to 40110 #

The inputs: a documented register range of 40108 to 40110, three holding registers, taken from the standard 4xxxx message example for FC03; a register format of 16 bits, two bytes each; a logging period of one minute, the target application's schedule; and a hypothetical first register that the controller displays as -2, to demonstrate signed decoding.

The rules in words: in the 4xxxx convention, the protocol starting address equals the documented reference minus 40001. A response carries two data bytes per requested register. A raw word above 32767 decodes as negative when the tag is signed 16-bit, by subtracting 65536.

The arithmetic: starting address 40108 - 40001 = 107. Data bytes: 2 per register, so 3 registers return 6 bytes. The controller's -2 travels on the wire as 65536 - 2 = 65534, and decodes back as 65534 - 65536 = -2.

The result: the client sends one FC03 request with starting address 107 and quantity 3, and a correct answer returns 6 data bytes covering registers 40108 through 40110. The first register stores as -2, not 65534; storing the raw word unsigned corrupts every average, minimum and report built on it.

The decision: when a tag the controller displays as negative arrives above 32767, set the client's register type to signed 16-bit or subtract 65536 from raw words above 32767 before the insert. When values come back shifted one position, the library wanted the offset, not the 4xxxx reference: send 107, not 40108. Record register, type and units in one map beside the application, because the next commissioning pass needs exactly that.

Prove the insert on its own #

Opening the database interactively under a maintenance account proves nothing about the logger's account. Test through the application's own connection path.

  1. Create numeric fields for the register values and a date/time field for the timestamp. Store the timestamp as a date/time value, never as a formatted string.
  2. Match the driver architecture to the application: a 64-bit application cannot load a 32-bit Access Database Engine provider. Check which driver is installed in the 64-bit ODBC Data Source Administrator before editing the connection string again.
  3. Run under the account that will run the logger and confirm write access to the database file and its folder, including the lock file the database engine creates beside it.
  4. Insert one known test record with a parameterized command: bind the three values as numbers and the timestamp as a date/time. Do not build SQL text by concatenating values and formatted dates, which breaks on regional decimal and date formats.
  5. Query the record back and compare all three values and the timestamp against the test inputs.

Commission against a test database and move to the production file only when the round trip matches and a failed write raises a visible diagnostic instead of vanishing. A desktop database serves a single logger well. When other applications must read the same rows or retention grows the file, plan the move to SQL Server, and compare plant historian selection by scale and support needs before upsizing.

Run the one-minute cycle without overlap #

Run acquisition and insert as one sequence: start the cycle, read the three registers in a single grouped FC03 transaction, validate the response, stamp the acquisition time, and insert the row. A timer tick can fire while the previous cycle's network or database call is still pending, so only one cycle may own that sequence: set a busy flag or disable the timer at cycle start and release it after the insert or the recorded failure.

Give the client a timeout around one second. A healthy answer on a plant LAN returns in tens of milliseconds, so one second sits far above normal and far below the one-minute period: a dead endpoint fails inside the same cycle instead of hanging the application.

Decide failure behavior once. On a failed read or insert, skip that minute's row and record the error; a one-minute logger loses nothing by skipping, and an unbounded retry queue hides the fault. Stamp values at acquisition, when the response validates, not at insert time, and never mix the two meanings in one column.

A grouped read cuts three transactions to one, but it does not guarantee a coherent snapshot: the controller may update its registers at different points in the scan. When the application needs values from one process moment, confirm the controller's update behavior and read a region the controller refreshes as a block.

Keep the logger off the control path #

The logger issues read function codes only. Nothing in the machine depends on it running: a stopped logger must not stop the machine, and fixing the logger must never require altering interlocks or controller logic. Commission it with the process supervised.

Where the connection crosses from an office or plant network into the control network, use the approved path and its rules. Do not disable network protections as a production fix; if the poll cannot cross, the fix is a permitted route through the boundary or a gateway on the control side, not an open port.

If the host is a dedicated cabinet-mounted computer rather than an office PC pressed into service, a fanless mini PC is the usual logger host for around-the-clock polling in a dusty enclosure.

The commissioning order and the decision #

  1. One FC03 read of the documented registers returns the expected count and values. Settle the offset convention and the signedness here, against values you set yourself.
  2. One parameterized test insert round-trips through the application's own connection under the account that will run the logger.
  3. The one-minute timer runs both steps under a reentrancy guard, skips and logs failed cycles, and stamps at acquisition.

The decision: when you need custom register handling, two-register values, or a schema the packaged tools cannot target, write the small application this way. When you only need standard logging, the no-code route that logs Modbus data on a Windows PC without programming reaches the same database with less to maintain. Keep either one read-only, guarded against overlap, and outside the control path.

Questions asked

Can the logger read 32-bit floats from holding registers?

Yes, with a two-register read. A 32-bit value occupies two consecutive 16-bit registers, and devices differ in which word arrives first, the high word or the low word. Write a known value from the controller side, read both registers, and watch which word changes with the integer part before committing to a combination order. Never copy a word order from another device's documentation.

Should the logger keep the Modbus connection open between cycles?

For one read per minute, connect, read, and close inside each cycle: it survives controller reboots and network interruptions without reconnect logic. A persistent connection is faster per transaction but must handle reconnection after any interruption, and some servers limit concurrent connections and refuse a client that never closes. At one-minute rates the handshake cost is negligible, so simplicity wins.

When does a desktop database stop being the right target?

When a second application must write, when several readers need concurrent access under load, or when retention grows the file toward its ceiling of about 2 GB. One row every minute produces roughly 525600 rows over a full year, which a desktop file holds, but make archiving part of the design. SQL Server handles concurrent writers and readers and scales past file limits.

Does the same approach work over Modbus RTU serial?

The register logic is identical: same map, same offset convention, same signedness decision. The transport changes, so a serial port and a station number replace the IP address and port 502, and responses are slower, so keep the timeout above the serial round trip at the chosen baud rate. Most client libraries expose both transports behind the same read call, so the application barely changes.

Keep reading

  • How-to

    Log Modbus data on a Windows PC without programming

    Map the signal path first: PLC and instrument values already on Modbus TCP or RTU go straight to a no-code logger on a Windows PC, while raw analog signals need a DAQ module in front of it. Configure one test channel, verify the logger against the device's own reading, then set a sampling period and file rollover you can prove end to end.

    Edge computing and IIoT

  • How-to

    Log production data from a panel PC to SQL Server

    Run Node-RED on the panel PC, read the production values straight from the controller, and insert one row per event into SQL Server with the mssql-plus node. Keep the panel's CSV-plus-FTP file relay only as a fallback, block duplicates with a last-record check and a unique key, and expect about 86,400 rows, roughly 8.6 MB, per day at one record per second.

    Edge computing and IIoT

  • Comparison

    Choosing edge storage for high-rate vibration data

    Keep the CSV-in-ZIP vibration archive that already works at 10 kHz, and treat Parquet as a candidate format, not a capacity fix. Move only after the Parquet writer proves exact sample fidelity, sustained throughput at the real acquisition rate, and recoverable completed archives after power loss. A format change is an engineering change with its own acceptance test, and compression in either format never repairs precision lost upstream.

    Edge computing and IIoT