BT San Technology

28 August 2026

Vision to PLC Handshake: Trigger, Result and Rejecting the Right Part

26 min read · Machine vision

Illustration: a conveyor with a camera station on the left and an air-jet reject further right pushing one carton into a chute, a PLC cabinet behind
AI-generated illustration

The camera says part 5 is bad, but the air blast removes part 6 from the conveyor. Or the bad part just rides past the reject gate and nobody knows. The camera's verdict is rarely the cause. The cause is that the verdict reaches the PLC after the part has already reached the gate, or that the PLC matches the verdict to the wrong part.

This article digs into rejecting parts on a moving conveyor: the time budget, a part queue tied to the encoder count, the pulse at the reject gate, a reject-by-default rule, dropping duplicate and stray results, and a heartbeat. The request, acknowledge and timeout signals between the processing board and the PLC are covered in the article on the Jetson-to-PLC handshake and are not repeated here. There is code you can run yourself, real output, and a Structured Text file that has never run on a real PLC. The article says plainly what is proven and what is not.

The real problem: the verdict is right, but the wrong part is rejected, or it is rejected too late

The conveyor does not stop and wait for the camera. The part has already passed the inspection point while the camera is still processing. The result comes back several hundred milliseconds later, and that time is not constant. The part keeps moving toward the reject gate, which is some distance away. The PLC has to know which part the result that just arrived belongs to, where that part is on the conveyor now, and when to open the air so it hits the right part.

Consider three hypothetical scenarios, not projects of any customer.

  • Suppose a box packing line uses a sequence counter: the PLC matches result number n to the nth box that passes the gate. One day the sensor trigger misses a box. The sequence shifts by one position, and every box after that is rejected incorrectly until someone resets the queue.
  • Suppose a factory makes the conveyor four times faster without moving the reject gate. The distance is the same but there is much less time. Results from the camera start arriving after the part has already passed the gate. No rule was set for this. Bad parts get through, or good parts get blown off in alternation.
  • Suppose the inspection program on the camera's computer hangs in the middle of a shift. There is no signal. The PLC does not check whether the camera is alive. No results arrive, and the system assumes nothing is wrong. All the parts in the shift pass through without anyone inspecting them.

All three cases are solved by the same principle: every part has an ID taken from the encoder count. Match results by ID, not by sequence. Set a decision deadline that waits for no one. And when in doubt, reject.

What the documents and references say

TopicWhat the reference saysEffect on our code
Part IDThe Cognex In-Sight (EtherNet/IP) documentation has the bits Trigger, Trigger Ack, Results Valid and Results Ack, and a 16-bit Inspection ID value, which is the ID of the image acquisition tied to a set of resultsEvery set of results must carry an ID that points back to the part. We use the encoder count as the ID
Track parts with an encoderA Vision Systems Design article on Cognex bottle-inspection systems states that an encoder on the conveyor feeds the reject-tracking logic, and the PLC uses it to track the bottle to the reject stationThe part queue advances by distance on the conveyor, not by time
Default is rejectThe same article states that the reject logic is failsafe: a bottle that fails inspection, or for which the camera returns no result, is rejectedIf no result arrives in time, reject the part and count it
Timers work when speed is constantAn example on Industrial Monitor Direct states that a PLC timer can delay the reject when the conveyor runs at constant speed. If the speed changes, it recommends an encoder or a distance-based calculation. It also says that an air reject needs accurate timing and knowledge of the part positionWe measure the actual speed and calculate in counts
Shift register advanced by encoder pulsesAn example on AC Automation uses a shift register clocked by encoder pulses. One pulse equals a fixed distance of conveyor. When the bit for a bad part reaches the position in front of the reject station, the program fires the air blastSame idea as our queue, but we store the count as an ID instead of a bit, so that results arriving out of order can be matched
Ordinary inputs cannot count fast pulsesMaple Systems states that regular inputs do not have a fast enough scan cycle to count fast signals. A high-speed counter (HSC) typically supports up to about 100 kHz and is paired with an encoderThe count at the signal edge must be latched by hardware, not read during the scan
Missed pulses mean lost positionWikipedia on the incremental encoder states that if the decoder cannot keep up, or there is noise, the counter no longer reflects the real position. It calls this a serious problem in many applicationsAn independent part count is needed to check that the queue still matches reality
Fixed-size FIFO bufferWikipedia on the circular buffer: fixed size, items are removed oldest first, and when full it can overwrite old data or refuse the write, depending on the applicationWe chose to refuse the insert, count it, and treat that part as untracked
Summarized from pages actually opened on 2026-11-21. See the full list at the end of the article. The values set in the code are hypothetical numbers, not values from the documents.

The Cognex documentation cited here describes the signal set of that camera model. The example in this article builds our own structure that is not tied to any brand. For the camera you actually use, read the bit names and message format from the documentation for that model.

Overview and files in the example

The example is in the folder examples/vision-plc-reject-handshake/. It runs on Node 24 with nothing to install and does not use the network. The PLC-side logic is written in TypeScript (tracker.ts), and a simulated world is built around it (conveyor, encoder, a camera with variable delay, a wobbling scan cycle, a delayed valve) to show what the logic does when things do not go as planned.

FilePurpose
budget.tsCalculates the time budget and the minimum reject-gate distance
tracker.tsPLC-side logic: queue by key, gate pulse, reject by default, drop duplicate results, heartbeat
sim.tsSimulated world. All numbers are hypothetical, with a fixed seed
scenarios.json7 scenarios, including failure cases
demo.tsRuns every scenario and prints a summary table
tracker.test.tsTest suite of 11 tests
reject_tracker.stThe same logic as Structured Text. Has never run on a real PLC
output.txtReal output of node demo.ts

The file reject_tracker.st has not been compiled or run on a real PLC. It was written step by step after tracker.ts so the two can be read side by side. What was tested is the TypeScript version, which simulates the same logic. Before real use, compile the ST in the tool of the brand you use and test it with the real machine.

Step 1: Time budget: how long does the camera have before the part reaches the gate

Before writing any logic, calculate whether it is possible at all. The part takes distance divided by speed to travel from the trigger point to the gate. But the result must reach the PLC before that, because time must be left for the PLC to scan and see the result, for the valve to actually open, and for the pulse to start half its width before the center of the gate. Then subtract a small margin for jitter.

budget.ts · lines 20–31
export function budget(b: BudgetIn): Budget {
  const mmPerMs = b.speedMmS / 1000;
  const travelMs = b.gateMm / mmPerMs;
  const leadMs = b.valveMs + b.scanMs + b.halfPulseMm / mmPerMs;
  const deadlineMs = travelMs - leadMs - b.marginMs;
  return {
    travelMs,
    deadlineMs,
    fireOffsetCounts: Math.round((b.gateMm - b.halfPulseMm) * b.cpm - (b.valveMs + b.scanMs) * mmPerMs * b.cpm),
    minGateMm: (latencyMs) => (latencyMs + b.marginMs + b.valveMs + b.scanMs) * mmPerMs + b.halfPulseMm,
  };
}
budget.ts: the time budget from speed, distance, valve time and scan time

At 500 mm/s with the gate 600 mm away, the part takes 1200 milliseconds to reach the gate. After subtracting 15 for the valve, 10 for the scan, 60 for half the pulse and 20 for margin, 1095 milliseconds remain for the camera to respond. This number is counted from the edge of the trigger signal, not from when the camera starts processing.

At 2000 mm/s with the same gate, only 240 milliseconds remain. If the camera takes as long as 270 in its worst cycle, the budget is not enough, and no PLC logic can help. You must move the gate farther away, speed up the camera, or slow the conveyor. The function minGateMm in the same file gives the minimum gate distance for a given delay.

Step 2: Part ID: the encoder count at the sensor edge

When the trigger sensor sees a part, have the hardware latch the encoder count at that signal edge (the latch function of a high-speed counter module, named differently by each brand). This value is the part's ID (key). It is sent to the camera and used to match the result that comes back. The point where the part will reach the gate is the key plus the gate distance in counts.

The encoder count is a 32-bit number that wraps around. Comparing with greater-than or less-than goes wrong when the count wraps through zero. Use a signed difference instead.

tracker.ts · lines 13–17
type Entry = { key: number; openAt: number; state: "wait" | "pass" | "fail" };
export type Counters = { fired: number; passed: number; timeouts: number; visionDown: number; duplicates: number; unmatched: number; overflow: number };

// Encoder is a 32-bit counter that wraps: compare with a signed difference, never with > or <.
export const diff = (a: number, b: number) => (a - b) | 0;
tracker.ts: the data type of a queue entry and the signed difference

This difference stays correct even when the count wraps past the boundary. The test suite has a test that starts the encoder at 2147482000, near the boundary, and the result must equal a normal run. In ST, the behavior of the DINT type on overflow depends on each brand's compiler. Check the manual of the brand you use.

sim.ts · lines 37–47
    for (const p of parts) if (p.trigMs === t) {
      p.x0 = x(t);
      if (p.spec.missTrigger) continue; // photo-sensor missed it: no latch, no camera trigger
      p.key = enc(t);
      trigQ.push(p.key);
      if (p.spec.lostResult) continue; // camera never answers
      const lat = p.spec.latencyMs ?? Math.round(s.camMeanMs + (rand() * 2 - 1) * s.camJitterMs);
      const msg = { key: p.key, fail: p.spec.defect };
      inbox.push({ at: t + lat, msg });
      if (p.spec.dupResult) inbox.push({ at: t + lat + 40, msg: { key: p.key, fail: false } }); // conflicting repeat
    }
sim.ts: when a part passes the sensor: a missed trigger, a camera that does not answer, and a conflicting duplicate result

Step 3: Queue by key: accept the trigger, match the result, drop results that belong to no one

On every scan, the PLC pushes the latched count into a FIFO queue, one entry per part. It takes incoming results and looks them up by key instead of taking the entry at the head of the queue. If the result for the second part arrives before the result for the first, it goes into the second part's slot. A missed trigger does not shift the later parts, because the entry for each later part has its own key.

tracker.ts · lines 48–57
    for (const key of triggers) {
      if (this.fifo.length >= g.depth) { this.c.overflow++; this.log(ms, "overflow", key, "fifo full, part untracked"); continue; }
      this.fifo.push({ key, openAt: (key + g.gateCounts - g.halfPulseCounts) | 0, state: "wait" });
    }
    for (const m of results) {
      const e = this.fifo.find((x) => x.key === m.key);
      if (!e) { this.c.unmatched++; this.log(ms, "discard", m.key, "no entry (late or stray)"); }
      else if (e.state !== "wait") { this.c.duplicates++; this.log(ms, "discard", m.key, `duplicate, first answer kept (${e.state})`); }
      else e.state = m.fail ? "fail" : "pass";
    }
tracker.ts: push the trigger into the queue, match the result by key, drop duplicate and stray results
  • Duplicate result: if the entry already has an answer, keep the first answer. Count it as a duplicate and log it. Do not overwrite, because a repeated message that conflicts with the original cannot tell you which one is right. The first answer at least came from a real inspection.
  • Stray or late result: no entry has a matching key (that part has already been decided and has left the queue, or never existed). Count it as a result with no owner and log it. Never apply it to another part.
  • Full queue: do not add the entry. Count an overflow and log it. That part is not tracked, which must trigger an alert.

A missed trigger is a case this logic cannot solve. The sensor does not see the part, so the PLC has no entry, the camera is not told to capture, and if that part is bad, it gets through and nobody knows. What you can do is have an independent part-counting sensor before the gate (in the simulated world, 50 mm before the gate) and compare it with the number of entries already decided. The difference is the number of untracked parts.

Step 4: Decide when the time comes: the default is reject

The entry at the head of the queue is decided when the part is near the start of the pulse, whether or not the result has arrived. If the result is fail, reject. If it is pass, let it through. If there is no result yet, reject and count it as a timeout. If the camera heartbeat is gone, reject and count it as vision-down. Choosing to reject when unsure means some good parts are discarded wrongly, but bad parts do not slip through silently. The two costs must be weighed for the actual job.

The decision point is moved earlier according to the speed measured in a 100-millisecond window, multiplied by the valve time plus one scan, so the air arrives when the part arrives, not when the PLC has just commanded it.

tracker.ts · lines 58–77
    // simplified: the output switches at scan time, so the start is quantised to one scan (5 mm at 500 mm/s, 20 mm at 2000 mm/s).
    // Production: a timed or high-speed output armed with the target count.
    // Look ahead by valve delay + one scan, at the measured speed, so the air arrives when the part does.
    const lead = Math.round(this.speedCpMs * (g.valveMs + g.scanMs));
    while (this.fifo.length > 0 && diff((enc + lead) | 0, this.fifo[0].openAt) >= 0) {
      const e = this.fifo.shift()!;
      let fire = true;
      let why = "timeout";
      if (!visionOk) { this.c.visionDown++; why = "vision-down"; }
      else if (e.state === "fail") { why = "result-fail"; }
      else if (e.state === "pass") { fire = false; why = "result-pass"; }
      else this.c.timeouts++;
      fire ? this.c.fired++ : this.c.passed++;
      this.log(ms, "decide", e.key, `${fire ? "fire" : "pass"} ${why}`);
      if (fire) {
        const end = (enc + 2 * g.halfPulseCounts) | 0;
        if (!this.on || diff(end, this.offAt) > 0) this.offAt = end;
        this.on = true;
      }
    }
tracker.ts: decide the entry at the head of the queue using the signed difference

Note that the loop decides only from the head of the queue. The queue is ordered by the order in which parts pass the sensor, which is the order in which they reach the gate. Results arriving out of order have no effect on the order of decisions.

Step 5: Pulse at the gate: centered on the part, width set by distance

The reject gate is not held open. It is a pulse centered on the part. The width is measured in encoder counts, so it gets shorter in time when the conveyor speeds up and stays the same in distance. Overlapping pulses are extended, not cut off.

tracker.ts · lines 78–79
    if (this.on && diff(enc, this.offAt) >= 0) this.on = false;
    return this.on;
tracker.ts: close the pulse when the count reaches the end point, then return the output value

In the simulated world, a pulse 600 counts wide (60 mm) equals 12 scans at 500 mm/s. The test suite checks that it falls between 11 and 13 scans. There is a limit to know about: the output changes during the scan, so the start time is rounded to the scan cycle. It can be off by 5 mm at 500 mm/s and 20 mm at 2000 mm/s. A real system should use a timed output or a high-speed output with the target count set in advance.

The mechanical side matters too. In the model, the air hits everything within 40 mm of the gate when the valve opens. If parts are spaced closer than about 70 mm, the neighboring part may be blown off as well. The tracking logic is not wrong. This is a limit of the blow-off head. Fix it with more spacing or a different reject method.

Step 6: Heartbeat: a silent camera must not be read as everything being fine

The camera sends a heartbeat message at intervals (in the simulated world, every 100 milliseconds). The PLC remembers the time of the last one. If more than 300 milliseconds pass, it treats the camera as gone. Every part is rejected and counted as vision-down. This is the third scenario above, and the operator should be alerted at once, rather than letting good parts keep being rejected.

tracker.ts · lines 41–47
    if (heartbeat) this.lastHb = ms;
    const visionOk = ms - this.lastHb <= g.hbTimeoutMs;
    if (ms - this.winMs >= 100) { // measure belt speed over a 100 ms window
      if (this.winMs > 0) this.speedCpMs = diff(enc, this.winEnc) / (ms - this.winMs);
      this.winMs = ms;
      this.winEnc = enc;
    }
tracker.ts: heartbeat and conveyor speed measurement in a 100-millisecond window

Step 7: The same logic in Structured Text

IEC 61131-3 defines four PLC programming languages, and one of them is Structured Text (ST). The logic above can be written directly in ST, as a function block with a 16-slot ring queue. What differs from the TypeScript, as noted in the file, is that it takes one trigger and one result per scan. A real system should drain the message queue completely on every scan.

reject_tracker.st · lines 56–94
(* 1. new part: append, or count an overflow *)
IF trigNew THEN
    IF n >= DEPTH THEN cntOverflow := cntOverflow + 1;
    ELSE
        idx := (head + n) MOD DEPTH;
        q[idx].key := trigCount; q[idx].openAt := trigCount + GATE_COUNTS - HALF_PULSE; q[idx].state := 0;
        n := n + 1;
    END_IF
END_IF

(* 2. new result: find by key, never by position *)
IF resNew THEN
    found := FALSE;
    FOR i := 0 TO n - 1 DO
        idx := (head + i) MOD DEPTH;
        IF q[idx].key = resKey THEN
            found := TRUE;
            IF q[idx].state <> 0 THEN cntDuplicate := cntDuplicate + 1;       (* keep the first answer *)
            ELSIF resFail THEN q[idx].state := 2; ELSE q[idx].state := 1; END_IF
        END_IF
    END_FOR
    IF NOT found THEN cntUnmatched := cntUnmatched + 1; END_IF               (* late or stray *)
END_IF

(* 3. decide the oldest entries whose time has come; signed DINT difference survives the wrap *)
lead := REAL_TO_DINT(speed * DINT_TO_REAL(VALVE_MS + SCAN_MS));
WHILE n > 0 AND ((enc + lead) - q[head].openAt) >= 0 DO
    fire := TRUE;
    IF NOT visionOk THEN cntVisionDown := cntVisionDown + 1;
    ELSIF q[head].state = 2 THEN ;
    ELSIF q[head].state = 1 THEN fire := FALSE;
    ELSE cntTimeout := cntTimeout + 1; END_IF                                 (* no answer: reject *)
    IF fire THEN
        cntFired := cntFired + 1;
        IF NOT gateOut OR ((enc + 2 * HALF_PULSE) - offAt) > 0 THEN offAt := enc + 2 * HALF_PULSE; END_IF
        gateOut := TRUE;
    ELSE cntPassed := cntPassed + 1; END_IF
    head := (head + 1) MOD DEPTH; n := n - 1;
END_WHILE
reject_tracker.st: steps 1 to 3 of the function block. Has never been compiled or run on a real PLC

Comparing counts in ST uses a difference tested against zero, the same as diff in TypeScript. But because the DINT behavior on overflow depends on the brand, test the wrap point on the compiler you actually use.

Real run: seven scenarios

The command node demo.ts runs seven scenarios in the simulated world. The result below is the real output from Node 24. All numbers are hypothetical and were not measured from a real machine.

output.txt

1 normal: 500 mm/s, gate 600 mm, camera 180 ms +/- 40
  budget: travel 1200 ms, result deadline 1095 ms after trigger, worst camera 220 ms -> fits
  P1  good   key=3000   pass result-pass     passed         ok
  P2  defect key=5000   fire result-fail     ejected -34mm  caught
  P3  good   key=7000   pass result-pass     passed         ok
  P4  defect key=9000   fire result-fail     ejected -34mm  caught
  P5  good   key=11000  pass result-pass     passed         ok
  counters: fired=2 passed=3 timeouts=0 visionDown=0 duplicates=0 unmatched=0 untrackedParts=0

2 late result: P2 answers after 1500 ms, P3 never answers
  budget: travel 1200 ms, result deadline 1095 ms after trigger, worst camera 220 ms -> fits
  P1  good   key=3000   pass result-pass     passed         ok
  P2  good   key=5000   fire timeout         ejected -35mm  WRONG REJECT
  P3  defect key=7000   fire timeout         ejected -32mm  caught
  P4  defect key=9000   fire result-fail     ejected -34mm  caught
  log t=2507ms discard key=5000: no entry (late or stray)
  counters: fired=3 passed=1 timeouts=2 visionDown=0 duplicates=0 unmatched=1 untrackedParts=0

3 missed trigger: the photo-sensor does not see P3 (a defective part)
  budget: travel 1200 ms, result deadline 1095 ms after trigger, worst camera 220 ms -> fits
  P1  defect key=3000   fire result-fail     ejected -30mm  caught
  P2  good   key=5000   pass result-pass     passed         ok
  P3  defect key=-      never seen by PLC    passed         ESCAPED
  P4  defect key=9000   fire result-fail     ejected -29mm  caught
  P5  good   key=11000  pass result-pass     passed         ok
  counters: fired=2 passed=2 timeouts=0 visionDown=0 duplicates=0 unmatched=0 untrackedParts=1

4 two parts close together: pitch 60 mm then 100 mm, results arrive out of order
  budget: travel 1200 ms, result deadline 1095 ms after trigger, worst camera 200 ms -> fits
  P1  defect key=3000   fire result-fail     ejected -30mm  caught
  P2  good   key=3600   pass result-pass     ejected -40mm  WRONG REJECT (collateral blast)
  P3  defect key=6600   fire result-fail     ejected -34mm  caught
  P4  good   key=7600   pass result-pass     passed         ok
  counters: fired=2 passed=2 timeouts=0 visionDown=0 duplicates=0 unmatched=0 untrackedParts=0

5 faster belt: 2000 mm/s, gate still at 600 mm, camera 230 ms +/- 40
  budget: travel 300 ms, result deadline 240 ms after trigger, worst camera 270 ms -> DOES NOT FIT
  P1  good   key=4000   pass result-pass     passed         ok
  P2  defect key=7000   fire result-fail     ejected -40mm  caught
  P3  good   key=10000  pass result-pass     passed         ok
  P4  defect key=13000  fire result-fail     ejected -40mm  caught
  P5  good   key=16000  fire timeout         ejected -40mm  WRONG REJECT
  log t=1075ms discard key=16000: no entry (late or stray)
  counters: fired=3 passed=2 timeouts=1 visionDown=0 duplicates=0 unmatched=1 untrackedParts=0

6 faster belt, gate moved to 1200 mm (same camera, 230 ms +/- 40)
  budget: travel 600 ms, result deadline 540 ms after trigger, worst camera 270 ms -> fits
  P1  good   key=4000   pass result-pass     passed         ok
  P2  defect key=7000   fire result-fail     ejected -40mm  caught
  P3  good   key=10000  pass result-pass     passed         ok
  P4  defect key=13000  fire result-fail     ejected -28mm  caught
  P5  good   key=16000  pass result-pass     passed         ok
  counters: fired=2 passed=3 timeouts=0 visionDown=0 duplicates=0 unmatched=0 untrackedParts=0

7 duplicate result, stray result, then the vision system goes silent at 2000 ms
  budget: travel 1200 ms, result deadline 1095 ms after trigger, worst camera 220 ms -> fits
  P1  good   key=3000   pass result-pass     passed         ok
  P2  defect key=5000   fire result-fail     ejected -29mm  caught
  P3  good   key=7000   fire vision-down     ejected -30mm  WRONG REJECT
  P4  good   key=9000   fire vision-down     ejected -32mm  WRONG REJECT
  log t=1054ms discard key=987654: no entry (late or stray)
  log t=1203ms discard key=5000: duplicate, first answer kept (fail)
  counters: fired=3 passed=1 timeouts=0 visionDown=2 duplicates=1 unmatched=1 untrackedParts=0

summary
  scenario                          parts           caught          escaped         wrong reject    default-reject  discarded       untracked       
  normal                            5               2               0               0               0               0               0               
  late result                       4               2               0               1               2               1               0               
  missed trigger                    5               2               1               0               0               0               1               
  parts close together              4               2               0               1               0               0               0               
  faster belt                       5               2               0               1               1               1               0               
  faster belt, farther gate         5               2               0               0               0               0               0               
  duplicate, stray, vision silent   4               1               0               2               2               2               0               
Real output run on 2026-11-21 with node demo.ts (Node 24)
  1. Scenario 1, normal: both bad parts are rejected (at the center of the gate, off by about 30 to 34 mm depending on the scan cycle). Good parts pass. No timeouts and no dropped results.
  2. Scenario 2, late results: P2 answers after the part has passed the gate, and P3 does not answer at all. Both are decided as timeouts and rejected. P2, a good part, is therefore rejected wrongly. The late result is dropped and logged as having no entry (the log line at 2507 milliseconds). It is not mixed up with another part.
  3. Scenario 3, missed trigger: P3 is bad but the PLC never saw it. It gets through. The untracked counter is 1, which is the only signal that says so. P4, which follows, is still rejected correctly because its key is tied to itself, not to the sequence.
  4. Scenario 4, closely spaced parts: P2 is a good part only 60 mm behind the bad P1. It is blown off as well, even though the logic decided it passes (the text collateral blast). This is a limit of the blow-off head, not a tracking error.
  5. Scenario 5, fast conveyor at 2000 mm/s: the budget shows DOES NOT FIT, and P5, a good part, is rejected wrongly because the result does not arrive in time.
  6. Scenario 6, gate moved to 1200 mm with the same camera: the budget becomes 540 milliseconds. All pass, and no good part is rejected wrongly.
  7. Scenario 7, duplicate result, stray result and a silent camera: the duplicate result that conflicts with the original is dropped, and the first answer (fail) is kept. The result with key 987654 has no owner and is dropped. After 2000 milliseconds with no heartbeat, the good parts P3 and P4 are rejected with the reason vision-down.

How the test suite works

Run it with node --test tracker.test.ts. There are 11 tests, and all pass. The test of the time budget checks the numbers 1095 and 240 directly.

tracker.test.ts · lines 33–40
test("results are matched by key, not by arrival order", () => {
  const { t, step } = rig();
  const a = 1600, b = 1700; // two parts triggered 100 counts apart
  step(1, [a, b]);
  step(1, [], [{ key: b, fail: false }]); // the second part's answer arrives first
  step(1, [], [{ key: a, fail: true }]);
  assert.deepEqual(t.fifo.map((e) => e.state), ["fail", "pass"]);
});
tracker.test.ts: results that arrive out of order must land in the slot given by their key
tracker.test.ts · lines 42–49
test("duplicate keeps the first answer, stray key is discarded, both logged", () => {
  const { t, step } = rig();
  step(1, [1600]);
  step(1, [], [{ key: 1600, fail: true }, { key: 1600, fail: false }, { key: 424242, fail: true }]);
  assert.equal(t.fifo[0].state, "fail");
  assert.equal(t.c.duplicates, 1);
  assert.equal(t.c.unmatched, 1);
});
tracker.test.ts: a duplicate result keeps the first answer, a stray result is dropped, and both are counted

The rest test the timeout, the pulse width, the heartbeat, a full queue, the wrap of the 32-bit count, and the outcomes of the scenarios in scenarios.json, including the case where moving the gate farther away keeps good parts from being rejected wrongly.

Using it for real: what the example does not do yet

  • Conveyor speed is not constant while accelerating and stopping. The example measures speed in a 100-millisecond window to move the decision point, but it does not simulate hard acceleration.
  • The pulse start follows the scan cycle. Use a timed or high-speed output, as noted in step 5.
  • The example treats a part as a point. A long or wide part has a leading edge and a trailing edge, so the position treated as the center must be adjusted.
  • The count is lost when the encoder slips or the belt slips. You need an independent part-counting sensor, and a procedure for when the queue is found not to match, for example clear the queue and reject every part that is in transit.
  • The reject gate is a device that really moves. Guards, emergency stops and safety functions are entirely separate from this logic, and a person qualified in machine safety must review them before real use.
  • Keep logs of dropped results, timeouts and vision-down so you can review them later. These numbers are an early warning that the time budget is getting tight.

Adapting it to other jobs

Three hypothetical examples, not anyone's real project.

A box packing line with a label check

Boxes pass a label camera that checks for a lot number and an expiry date. The blow-off head is one meter away. Start from step 1: calculate whether the camera's slowest inspection time is enough at the line's top speed. If not, move the blow-off head before touching the logic.

A plastic parts line with several lanes

The inspection result is more than pass or fail, for example grade A, grade B and scrap. Add a grade value to the queue entry and use several gates, each with its own distance. Each entry is decided against the gate that matches its grade. The principle of matching by key and the default do not change.

A line where the camera is on an external computer

When results travel over a network, the delay varies more than with a smart camera wired directly. Measure the real delay while the line runs for several hours. Use the worst value, not the average, in step 1, and use the heartbeat to check that the network is still usable.

Common mistakes

  • Matching results to parts by arrival order. After a single missed trigger, every part after it is the wrong one.
  • Using a timer instead of distance, and then the conveyor changes speed.
  • Not calculating the time budget, and then trying to fix a mechanical problem with code.
  • Letting parts through when there is no result, which lets bad parts escape when the camera is slow or stopped.
  • Keeping the latest duplicate result instead of the first, so the verdict changes by itself when messages arrive twice.
  • Comparing counts with greater-than or less-than, so the system breaks when the count wraps, which may be several weeks after installation.
  • Reading the count during the scan instead of latching it in hardware. The value is off by the scan cycle.
  • Having no independent part counter, so there is no way to know that the queue does not match reality.

Checklist before connecting the camera to the PLC

  1. Calculate the time budget at top speed and the worst camera time. Is there any margin left?
  2. Latch the encoder count with a high-speed input at the sensor signal edge.
  3. Send the key to the camera, and have every set of results come back with the key.
  4. Match results by key, not by sequence. Keep the first of duplicate results. Drop and log stray results.
  5. Set the default to reject when there is no result before the decision point.
  6. Have a heartbeat and a rule for when the camera goes silent, with an alert.
  7. Compare counts with a signed difference. Test across the count wrap point.
  8. Measure the pulse width in counts, and check that neighboring parts are not blown off as well.
  9. Have an independent part-counting sensor before the gate, to compare against the number of decided entries.
  10. Test top speed, tightest spacing, late results, a stopped camera, and restarting the line, then have a person qualified in machine safety review it before use.

Caution: all the numbers in this article (speed, distance, camera time, valve time) are hypothetical and were not measured from a real machine. The ST file has never run on a real PLC. The results from the simulated world are not a guarantee that your machine will behave this way. You must measure and test with the real conveyor, camera and blow-off head.

References

  1. Cognex In-Sight — EtherNet/IP I/O module reference (Trigger, Trigger Ack, Results Valid, Inspection ID, Results Ack) (accessed 2026-11-21)
  2. Vision Systems Design — Cognex In-Sight bottle inspection (encoder reject tracking, failsafe reject) (accessed 2026-11-21)
  3. AC Automation — PLC example: shift register conveyor reject (accessed 2026-11-21)
  4. Industrial Monitor Direct — PLC sensor selection for conveyor reject stations (accessed 2026-11-21)
  5. Maple Systems — What is a high speed counter and how is it used with an encoder (accessed 2026-11-21)
  6. Wikipedia — Incremental encoder (quadrature counting, lost position) (accessed 2026-11-21)
  7. Wikipedia — Circular buffer (fixed-size FIFO, overflow behaviour) (accessed 2026-11-21)
  8. Wikipedia — IEC 61131-3 (PLC languages including Structured Text) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer