Troubleshooting
Capture 1 ms PLC samples to InfluxDB without data loss
Short answer
Polling a live value at any rate cannot preserve 1 ms PLC samples, because acquisition timing then belongs to the reader. Run the sampling in the PLC's 1 ms task, publish each filled value-and-timestamp batch behind a counter such as buffer_id, and let Node-RED transfer a batch only when that counter changes. Write one database point per sample with its own timestamp, and size batches so the consumer always finishes before the next one completes.

On this page
- Why does polling the live PLC value miss the samples between reads?
- How do I sample inside the PLC's fast task instead?
- How long does one batch take to fill?
- How does Node-RED take a batch without racing the PLC?
- How do I write the arrays to InfluxDB so every sample keeps its own point?
- Why does the first batch after a restart look wrong?
- What should I check before trusting the recorded trend?
- Questions asked
Fast data recorded by polling a live PLC value is fast polling, not millisecond data: the reader's cycle decides what survives. To capture true millisecond behavior, sampling has to run where the timing is exact — inside the PLC's own 1 ms task — while the consumer moves finished batches instead of chasing a moving value. The working pattern is a daq function block that fills internal value and timestamp arrays, copies them out behind a buffer counter, and a Node-RED flow that transfers each batch to local InfluxDB only when that counter changes. The result is one verifiable database point per sample, with the acquisition interval set in the PLC and the transfer rate chosen independently. The sections below give the code, the batch arithmetic, the hand-off rules, and the checks that make the trend trustworthy.
Why does polling the live PLC value miss the samples between reads? #
When Node-RED polls a live value it records only whatever the variable holds at that instant, so any change that begins and ends between two polls never reaches the database, and a faster poll narrows that blind window without ever closing it.
The timing of acquisition belongs to whoever runs the loop, and in this pattern that is the reader, not the process. A scalar read through the controller's data interface proves connectivity in seconds; it proves nothing about high-speed acquisition. The direction has to flip: the PLC, which executes on a fixed schedule, acquires, and the consumer collects finished results. Subscription transfer applies the same idea from the protocol side, pushing each update as it happens instead of waiting to be asked — that is the argument behind OPC UA subscription updates beat polling for PLC input changes. The build below applies it inside the controller: sample in the fast task, publish per batch.
How do I sample inside the PLC's fast task instead? #
Create a function block called daq that stores a value and a timestamp into internal arrays on every trigger change and copies them out when the batch is full, then call it from fast_task, a task configured to run every millisecond.
The demonstration runs on one controller with the ctrlX PLC App, ctrlX InfluxDB App, and ctrlX Node-RED App installed, plus the Util library added in ctrlX PLC Engineering: the block calls Util.SysTimeRtcHighResGet for the timestamp and Util.SysMemCpy for the batch copies. In the task configuration, set the task's interval to 1 ms and assign fast_task to it; the controller's scheduler runs and monitors the configured tasks. The attribute statements in the variable list export each symbol to the runtime's data interface, which is what lets Node-RED read them.
The function block, trimmed to the variables the logic uses:
FUNCTION_BLOCK daq
VAR_INPUT
num_samples : UINT := 1000;
input_value : UINT;
trigger : UDINT;
END_VAR
VAR_OUTPUT
buffer_id : INT := 0;
buffer_value : ARRAY [0..10000] OF UINT;
buffer_timestamp : ARRAY [0..10000] OF ULINT;
END_VAR
VAR
sample : INT := 0;
rtc : ULINT;
trigger_old : UDINT := 0;
buffer_internal_value : ARRAY [0..10000] OF UINT;
buffer_internal_timestamp : ARRAY [0..10000] OF ULINT;
END_VAR
Util.SysTimeRtcHighResGet(pTimestamp := rtc);
IF trigger <> trigger_old THEN
buffer_internal_value[sample] := input_value;
buffer_internal_timestamp[sample] := rtc;
sample := sample + 1;
END_IF
IF sample >= num_samples THEN
sample := 0;
Util.SysMemCpy(pDest := ADR(buffer_value),
pSrc := ADR(buffer_internal_value),
udiCount := num_samples * SIZEOF(input_value));
Util.SysMemCpy(pDest := ADR(buffer_timestamp),
pSrc := ADR(buffer_internal_timestamp),
udiCount := num_samples * SIZEOF(rtc));
buffer_id := buffer_id + 1;
END_IF
trigger_old := trigger;
The global variable list:
VAR_GLOBAL
{attribute 'symbol' := 'readwrite'} bStart : BOOL;
{attribute 'symbol' := 'read'} i : UINT;
{attribute 'symbol' := 'read'} trigger : UINT := 0;
{attribute 'symbol' := 'readwrite'} sample_interval : UINT := 10;
{attribute 'symbol' := 'read'} num_samples : UINT := 5000;
{attribute 'symbol' := 'read'} buffer_id : INT;
{attribute 'symbol' := 'read'} buffer_value : ARRAY [0..10000] OF UINT;
{attribute 'symbol' := 'read'} buffer_timestamp : ARRAY [0..10000] OF ULINT;
END_VAR
The program, called from the fast task:
PROGRAM fast_task
VAR
daq : daq;
END_VAR
IF bStart THEN
IF i MOD sample_interval = 0 THEN
trigger := trigger + 1;
END_IF
i := i + 1;
END_IF
daq(
num_samples := num_samples,
input_value := i,
trigger := trigger,
buffer_id => buffer_id,
buffer_value => buffer_value,
buffer_timestamp => buffer_timestamp
);
One trigger change stores exactly one sample: the block compares trigger with trigger_old, writes input_value and the clock reading rtc at the same index, and only when the count reaches num_samples does it copy both arrays out and step buffer_id. The demo measures the counter i; once the path is proven, replace input_value := i with the real measurement and let trigger follow the real event.
What each control variable decides:
bStart— true starts acquisition; going false stops the trigger generation but leaves the daq call and any partly filled batch untouched.sample_interval— samples on every Nth task execution: the GVL value of 10 means one sample every ten executions and 1 means every execution; never allow 0, because the modulo test has no defined result for it.num_samples— points per batch; the block's default is 1000, but the program passes the GVL value in, so the GVL declaration is the active setting.trigger— each new value stores exactly one sample; the demo increments it on schedule, a real application changes it on the event itself.buffer_id— rises by one per finished batch; it is the only signal the consumer needs to watch.
How long does one batch take to fill? #
Fill time is num_samples * sample_interval * task period; with the GVL's 5,000 samples that works out to 50 seconds, which is also the deadline your consumer has to beat on every batch.
Worked example, with the GVL exactly as declared: 5,000 samples per batch * 10 task executions per sample * 1 ms per execution = 50,000 ms = 50 s to fill one batch. The average database rate is batch size over fill time: 5,000 / 50 s = 100 points per second. Cut sample_interval to 1 for full-rate capture and the fill time drops tenfold to 5 s, raising the average to 5,000 / 5 s = 1,000 points per second. The completing task execution also performs both copies: 5,000 * 2 bytes for the UINT values plus 5,000 * 8 bytes for the ULINT timestamps = 50,000 bytes moved inside a single cycle, so check the task's execution time on a publication cycle, not only on an ordinary one.
Smaller batches cut latency and the overwrite window but multiply transfers and database requests. Budget the whole hand-off — read both arrays, build the points, write, confirm — to finish within a quarter of the fill time, leaving the rest for retries and a slow database. If the same host also feeds dashboards or a second collector, size it for the burst each batch creates rather than the average; the walkthrough on sizing an edge PC for oversampled PLC data to InfluxDB works that calculation out.
How does Node-RED take a batch without racing the PLC? #
Watch the exported symbol buffer_id, and when its value changes read buffer_value and buffer_timestamp together once: a change means the block has finished writing that batch, so both arrays are stable while your flow copies them.
- Read
buffer_idat a fixed interval — polling the counter is fine; it is the samples that must never be polled. - On a change, compare the new value with the last one seen: a step of exactly 1 is one fresh batch, and a step of more than 1 means the PLC overwrote batches the flow never collected — record the gap, because those samples are unrecoverable.
- Read
buffer_valueandbuffer_timestampback to back in the same flow, with nothing else between them. - Build one point per index, write to the database, and update the stored last-seen counter only after the write is confirmed.
The external buffer is single: the block reuses it at the next completion, and no acknowledgement can call a batch back. The quarter-of-the-fill-time budget keeps a healthy consumer clear of that collision, and the counter gap in step 2 is how you detect the day it happens anyway. This producer-finishes, consumer-collects hand-off is the same pattern historian integrators use when they publish collected batches downstream, so the design is not specific to one controller.
How do I write the arrays to InfluxDB so every sample keeps its own point? #
Unroll the two arrays into one database point per index, pairing each timestamp with the value at the same index from position 0 through num_samples - 1, and never write the array itself as a single field, which stores one point instead of thousands.
A write that passes the array as one value produces exactly that: one point, holding the last element — the same failure described in why InfluxDB keeps only the last record of a Node-RED array write.
The timestamp needs two decisions. First, SysTimeRtcHighResGet returns the high-resolution UTC clock reading into the ULINT passed via pTimestamp, and the installed Util library documentation states the unit and epoch — confirm both before the first write, because line protocol interprets each integer timestamp according to the write's precision, and the wrong setting shifts every sample by orders of magnitude. Second, keep the value out of JavaScript numbers on the way through Node-RED: exact integer representation ends at 2^53 - 1 = 9,007,199,254,740,991, and if the unit is nanoseconds a current stamp is about 1.7 * 10^18, so a Number silently alters it — carry the timestamp as a string end to end and let the database convert.
Why does the first batch after a restart look wrong? #
Setting bStart false stops the trigger generation but not the daq call, and nothing clears a partly filled batch, so after restarting the block appends new samples to the old ones and publishes a batch whose timestamps straddle the pause.
Decide the policy instead of inheriting the demonstration's. For process recording I discard the partial batch at stop: reset the sample index when bStart goes false, so every published batch is complete and gap-free and a restart opens a fresh one. Retaining the partial batch is also defensible where a short batch is acceptable, provided the analysis knows the first batch after a pause is partial. Verify either choice on that first batch: differencing consecutive timestamps shows the pause as one delta equal to the outage length.
One safety note: this recorder documents behavior for analysis, and a lost, delayed, or merged batch must never be able to influence a stop or a guard — safety functions stay on hardware certified for them.
What should I check before trusting the recorded trend? #
Prove the chain in order — task, batch, transfer, write, clock — and accept the data only when the timestamp deltas inside a batch match the configured spacing and every batch carries exactly num_samples points.
- Task execution: read the runtime's task diagnostics and confirm the actual period and execution time, especially on the cycle that publishes a batch and moves both copies.
- Sample spacing: difference consecutive timestamps within one batch; the deltas must equal the configured spacing, and a single long delta marks a stop, a clock adjustment, or a stalled consumer.
- Clock identity: compare one captured timestamp with the controller clock and with the value the database shows after conversion, and test wall-clock adjustments separately from steady-state capture.
- Batch integrity: the point count per batch equals num_samples and buffer_id advanced by exactly 1 between collections.
- End to end: force one known trigger change and find that sample at the expected time in the database; if points still go missing after that, work through the checklist for missing data in a Node-RED InfluxDB Grafana stack.
Decision: with sampling in the fast task, the hand-off inside the quarter-fill budget, the arrays unrolled to one point per sample, and these checks passing at both spacing settings, the local InfluxDB trend is trustworthy at the full task rate — and the counter-gap check plus the discard-at-stop policy are what keep it trustworthy the week something slows down.
Questions asked
Can something other than Node-RED consume the batches?
Yes. Any client that can read the controller's exported symbols can watch buffer_id and pull both arrays when it changes: an OPC UA client, a script against the runtime's data interface, or a second runtime. Node-RED is only the demonstrated consumer. The rules on the consumer side stay the same either way: react to the counter, read the value and timestamp arrays together, and treat a counter jump of more than one as an overwritten batch.
What moment does the stored timestamp actually mark?
It marks the software acquisition instant, when the fast task observed the trigger change, not the moment the input module converted the physical signal. A change picked up on the next task execution lands less than one task period after the physical event, but the offset exists. If an application needs input-level time stamps, they must come from I/O hardware whose documentation states its own timestamping behavior; this function block cannot provide them.
How large should num_samples be?
Decide from the consumer's worst-case read, build, and write time, not from the array limit. The declared arrays hold 10,001 elements each, so num_samples may run from 1 to 10,001, but a smaller batch shortens the window in which a stalled consumer loses samples and increases the number of database writes. Keep the fill time comfortably longer than the transfer budget and confirm the margin with the counter-gap check.
What write rate must the database host be planned for?
Plan for the sample rate, which batch size does not change: at interval 10 the recorder averages 100 points per second and at interval 1 it averages 1,000, however many points each batch holds. Batch size only sets how often Node-RED writes and how large each write is. Leave headroom for each batch arriving as one burst and for retention growth on the host.
Can the block record signed or floating-point signals?
Not as published: input_value and the value arrays are UINT, so a signed, real, or multichannel signal needs the input and the array element type changed to match, keeping both copy lengths derived from SIZEOF of the type actually stored, as the block already does. The trigger, counter, and index logic are type-independent. The demo counter i is a stand-in signal, so replace the input_value wiring before recording anything real.


