26 分钟阅读 · 机器视觉

相机说第 5 个工件有缺陷,但气流吹掉的却是第 6 个,或者有缺陷的工件直接从剔除闸口旁边过去了,却没有人知道。相机的检测结果往往不是根源,根源是检测结果比工件更晚到达 PLC,或者 PLC 把结果与工件配错了对象。
本文深入讲解在运行中的传送带上剔除不良品:时间预算、与编码器计数值绑定的工件队列、剔除闸口的脉冲、默认剔除、丢弃重复结果和游离结果,以及 heartbeat。处理板与 PLC 之间的确认信号和 timeout,已在介绍 Jetson 与 PLC 握手的文章里讲过,这里不再重复。文中有可自行运行的代码、真实运行结果,以及一份从未在真实 PLC 上运行过的 Structured Text 文件,文章会直接说明哪些已经证实,哪些尚未证实。
真正的问题:检测结果正确,却剔除了错误的工件,或者来不及剔除
传送带不会停下来等相机。工件通过检测点后相机仍在处理,结果要在几百毫秒之后才会回来,而且这个时间并不固定。工件继续往前走,到达较远处的剔除闸口。PLC 必须知道刚到的结果属于哪一个工件、该工件此刻在传送带上的什么位置,以及什么时候开启气吹才能正好打中它。
来看三个假设场景,并非任何客户的项目。
- 假设装箱线使用顺序计数器:PLC 把第 n 个检测结果对应到通过闸口的第 n 个箱子。有一天触发传感器漏掉了一个箱子,顺序整体错开一位,此后的每个箱子都被剔除错了对象,直到有人重置队列。
- 假设工厂把传送带速度提高到四倍,却没有移动剔除闸口。距离不变,时间却少了,相机的结果开始在工件已经过了闸口之后才到。系统没有事先定好规则,有缺陷的工件漏了过去,或者好工件与坏工件被交替吹掉。
- 假设相机电脑上的检测程序在班次中途卡死,没有信号,PLC 没有检查相机是否还活着,没有结果进来,系统以为什么都没坏。整个班次的工件都在没人检测的情况下通过了。
这三种情况用同一条原则就能解决:每个工件都有一个来自编码器计数值的身份编码,用编码而不是用顺序来配对结果,有一个不等任何人的判定期限,不知道的时候就剔除。
文档与参考资料怎么说
| 主题 | 参考资料的说法 | 对我们代码的影响 |
|---|---|---|
| 工件编码 | Cognex In-Sight(EtherNet/IP)文档有 Trigger、Trigger Ack、Results Valid、Results Ack 这些位,以及 16 位的 Inspection ID 值,它是与一组结果绑定的拍摄编码 | 每一组结果都必须有编码可以回溯到工件,我们用编码器计数值作为编码 |
| 用编码器跟踪工件 | Vision Systems Design 关于 Cognex 瓶子检测系统的文章指出,传送带上的编码器为剔除跟踪逻辑提供输入,PLC 用它来跟踪瓶子到达剔除工位 | 工件队列按传送带上的距离前进,而不是按时间 |
| 默认值是剔除 | 同一篇文章指出剔除逻辑是 failsafe:检测不通过的瓶子,或相机没有返回结果的瓶子,都会被剔除 | 没有及时拿到结果就剔除,并计数 |
| 计时器在速度恒定时可用 | Industrial Monitor Direct 上的示例指出,传送带匀速运行时,可以用 PLC 的计时器来延迟剔除;速度会变化时,建议用编码器或按距离计算;气吹剔除需要准确的时机并且要知道工件位置 | 我们测量实际速度,并换算成计数值 |
| 随编码器脉冲移位的 shift register | AC Automation 上的示例使用 shift register,以编码器脉冲作为时钟信号,一个脉冲等于传送带上固定的距离;当不良品对应的位移到剔除工位前方的位置时,程序命令气吹 | 与我们的队列是同一个思路,但我们保存的是计数编码而不是位,以便配对到达顺序错乱的结果 |
| 普通输入跟不上高速脉冲 | Maple Systems 指出,普通输入的扫描周期不足以对快速信号计数;高速计数器(HSC)一般最高支持约 100 kHz,并与编码器配对使用 | 信号沿处的计数值必须由硬件锁存,而不是在扫描时读取 |
| 漏计脉冲就是丢失位置 | Wikipedia 关于 incremental encoder 的条目指出,如果解码器来不及计数,或有噪声干扰,计数器就不再反映真实位置,在许多应用中被称为严重事故 | 必须有独立的工件计数,用来检查队列是否仍与实际一致 |
| 固定大小的 FIFO 缓冲区 | Wikipedia 关于 circular buffer 的条目:大小固定,先移出最旧的,满了之后可以覆盖旧数据,也可以拒绝写入,视应用而定 | 选择拒绝添加,计数,并视为该工件没有被跟踪 |
所引用的 Cognex 文档说明的是该型号相机的信号集。本文的示例搭建了我们自己的框架,不绑定任何品牌,实际使用的相机的位名称和消息格式必须阅读该型号的文档。
概览与示例中的文件
示例位于 examples/vision-plc-reject-handshake/ 文件夹,用 Node 24 运行,无需安装任何东西,也不使用网络。PLC 一侧的逻辑用 TypeScript 编写(tracker.ts),并围绕它构建了模拟环境(传送带、编码器、速度不稳定的相机、抖动的扫描周期、有延迟的阀门),以便看出当事情不按理想发展时,逻辑会怎么做。
| 文件 | 作用 |
|---|---|
| budget.ts | 计算时间预算和剔除闸口的最小距离 |
| tracker.ts | PLC 一侧的逻辑:按 key 排列的队列、闸口脉冲、默认剔除、丢弃重复结果、heartbeat |
| sim.ts | 模拟环境,所有数字均为假设,使用固定的 seed |
| scenarios.json | 7 个场景,含故障情形 |
| demo.ts | 运行所有场景,打印汇总表 |
| tracker.test.ts | 测试集,共 11 项 |
| reject_tracker.st | 同样的逻辑,以 Structured Text 写成,尚未在真实 PLC 上运行 |
| output.txt | node demo.ts 的真实运行结果 |
reject_tracker.st 文件没有在真实 PLC 上编译或运行,是按 tracker.ts 的步骤逐步编写的,以便对照阅读。通过测试的是 TypeScript 版本,它模拟同样的逻辑。实际使用前,必须把 ST 拿到所用品牌的工具中编译,并用实物测试。
第 1 步 时间预算:工件到达闸口之前,相机有多少时间
在写任何逻辑之前,先算一算是否可行。工件从触发点走到闸口所需的时间等于距离除以速度,但结果必须在此之前到达 PLC,因为还要留出时间让 PLC 的扫描看到结果、阀门真正打开,以及从闸口中点之前半个脉冲宽度开始的脉冲,然后再扣掉一点用于抖动的余量。
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,
};
}在 500 毫米/秒、闸口相距 600 毫米的情况下,工件需要 1200 毫秒到达闸口,扣除阀门 15、扫描 10、半个脉冲 60 和余量 20 之后,剩下 1095 毫秒给相机作答。这个数字是从触发信号的信号沿开始计算的,而不是从相机开始处理的时刻算起。
在 2000 毫米/秒、闸口不变的情况下,只剩 240 毫秒。如果相机在最差的一轮中慢到 270,预算就不够,没有任何 PLC 逻辑能帮上忙。必须把闸口移远一点、让相机更快,或者降低速度。同一文件中的 minGateMm 函数,可以给出在指定延迟下闸口的最小距离。
第 2 步 工件编码:传感器信号沿处的编码器计数值
当触发传感器看到工件时,让硬件在该信号沿处锁存编码器计数值(高速计数模块的 latch 功能,各品牌名称不同)。这个值就是工件的编码(key),用于发送给相机,并用来配对返回的结果。工件将到达闸口的位置点,等于 key 加上以计数为单位的闸口距离。
编码器的计数值是会回绕的 32 位数字,用大于或小于来比较,在经过零点时会出错,应改用带符号的差值。
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;即使计数值回绕过边界,这个差值仍然正确。测试集中有一项让编码器从 2147482000 开始,靠近边界,结果必须与正常情况相同。在 ST 中的 DINT 类型,溢出时的行为取决于各品牌的编译器,必须按所用品牌的手册检查。
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
}第 3 步 按 key 排列的队列:接收触发、配对结果、丢弃不属于任何人的结果
PLC 每次扫描,都把锁存的计数值放入 FIFO 队列,每个工件一个条目,并接收进来的结果,用 key 去查找,而不是取队首的条目。如果第二个工件的结果比第一个先到,它就放进第二个工件的位置。漏掉的触发不会让后面的工件错位,因为后面工件的条目有它自己的 key。
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";
}- 重复结果:如果该条目已经有了答案,就保留第一个答案,计为重复结果并记录,不覆盖,因为与原先结果相矛盾的重复消息,无法判断哪个才对,而第一个答案至少来自一次真实的检测。
- 游离或迟到的结果:没有 key 相符的条目(该工件已被判定并离开队列,或者从来没有过),计为无主结果并记录,绝不能拿去用在其他工件上。
- 队列已满:不添加条目,计入 overflow 并记录。该工件没有被跟踪,这必须触发告警。
漏触发是这套逻辑解决不了的情况:传感器没有看到工件,PLC 就没有条目,相机不会被命令拍照,如果这个工件有缺陷,它就在没人知道的情况下漏了过去。能做的是在闸口之前放一个独立计数工件的传感器(在模拟环境中是闸口前 50 毫米),再与已判定的条目数量比较。差值就是没有被跟踪的工件。
第 4 步 到时间就判定:默认值是剔除
队首的条目,在工件临近脉冲起点时被判定,无论结果是否已经到达。如果结果是不通过,就剔除;通过,就放行;还没有结果,就剔除并计为 timeout;如果相机的 heartbeat 消失,就剔除并计为 vision-down。选择在不知道时剔除,会使部分好工件被错误地丢弃,但有缺陷的工件不会悄悄漏过去。这两种成本要根据实际工作来权衡。
判定点按在 100 毫秒窗口内测得的速度,乘以阀门时间再加一次扫描来提前,使气流到达时正好是工件到达的时候,而不是 PLC 刚下命令的时候。
// 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;
}
}请注意,循环只从队首进行判定。队列按工件通过传感器的顺序排列,这也是到达闸口的顺序,所以结果无论怎样乱序到达,都不会影响判定的顺序。
第 5 步 闸口的脉冲:中心对准工件,宽度按距离
剔除闸口不是一直开着,而是一个以工件为中心的脉冲。宽度以编码器的计数值来衡量,所以传送带变快时,以时间计的宽度会自动变短,以距离计的宽度则保持不变。相互重叠的脉冲会被延长,而不是被截断。
if (this.on && diff(enc, this.offAt) >= 0) this.on = false;
return this.on;在模拟环境中,脉冲宽度为 600 计数(60 毫米),在 500 毫米/秒时等于 12 次扫描。测试集检查它介于 11 到 13 次扫描之间。有一个必须知道的限制:输出在扫描时才改变,所以起始时机会按扫描周期取整,在 500 毫米/秒时可能偏差 5 毫米,在 2000 毫米/秒时可能偏差 20 毫米。真实使用时,应使用定时输出,或预先设定目标计数的高速输出。
机械层面也很重要。在模型中,阀门打开时,气流会打中距闸口 40 毫米范围内的一切。如果工件之间的间距小于约 70 毫米,相邻的工件可能被一起吹掉。跟踪逻辑没有错,这是吹气头的限制,必须靠拉开间距或改变剔除方式来解决。
第 6 步 heartbeat:相机沉默,不能被解读为一切正常
相机定期发送 heartbeat 消息(在模拟环境中每 100 毫秒一次),PLC 记住最后一次收到的时间。如果超过 300 毫秒,就认为相机不在了,所有工件都被剔除并计为 vision-down,这就是上面的第三个场景,应立即向维护人员告警,不能让它一直把好东西剔除下去。
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;
}第 7 步 同样的逻辑,用 Structured Text 来写
IEC 61131-3 规定了四种 PLC 编程语言,Structured Text(ST)是其中之一。上面的逻辑可以直接用 ST 写出来,做成一个带 16 格环形队列的功能块。与 TypeScript 的不同之处,如文件中所写,是每次扫描只接收一个触发和一个结果,真实使用时应在每次扫描中把消息队列取空。
(* 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在 ST 中比较计数值,用差值再与零比较,与 TypeScript 中的 diff 一样,但由于 DINT 溢出时的行为取决于品牌,必须在实际使用的编译器上测试回绕点。
实际运行:七个场景
node demo.ts 命令在模拟环境中运行七个场景,下面是用 Node 24 实际运行的结果。所有数字均为假设,并非在真实机器上测得。
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 - 场景 1 正常:两个有缺陷的工件都被剔除(打在闸口中间,偏差大约 30 到 34 毫米,取决于扫描周期),好工件通过,没有 timeout,没有被丢弃的结果。
- 场景 2 结果迟到:P2 在工件已经过了闸口之后才作答,P3 完全没有作答,两者都被判定为 timeout 并被剔除。P2 是好工件,所以被错误地剔除。迟到的结果被丢弃,并记录为没有条目(log 的第 2507 毫秒那一行),没有与其他工件混在一起。
- 场景 3 漏触发:P3 有缺陷,但 PLC 从未看到它,它漏了过去。untracked 计数器为 1,这是唯一能告知此事的信号。随后的 P4 仍被正确剔除,因为 key 绑定的是它自己,而不是顺序。
- 场景 4 工件紧挨着:P2 是好工件,与有缺陷的 P1 只相距 60 毫米,尽管逻辑判定它通过,仍被一起吹掉(字面上的 collateral blast)。这是吹气头的限制,不是跟踪的错误。
- 场景 5 传送带加速到 2000 毫米/秒:预算显示 DOES NOT FIT,而 P5 是好工件,因为结果来不及,被错误地剔除。
- 场景 6 把闸口移到 1200 毫米,相机不变,预算剩 540 毫秒,全部通过,没有好工件被错误剔除。
- 场景 7 重复结果、游离结果与相机沉默:与原先结果相矛盾的重复结果被丢弃,保留第一个答案(fail)。key 为 987654 的结果没有归属,被丢弃。2000 毫秒之后没有 heartbeat,好工件 P3 和 P4 以 vision-down 为由被剔除。
测试集如何运作
用 node --test tracker.test.ts 运行,共 11 项,全部通过。检查时间预算的那一项直接核对 1095 和 240 这两个数字。
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"]);
});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);
});其余检查 timeout、脉冲宽度、heartbeat、队列已满、32 位计数值的回绕,以及 scenarios.json 文件中各场景的结果,包括闸口移远后,好工件不再被错误剔除的情形。
用于真实生产:本示例尚未做到的事
- 加速和停止时,传送带速度并不恒定。示例在 100 毫秒窗口内测量速度来提前判定点,但没有模拟剧烈的加速。
- 脉冲的起点取决于扫描周期,必须使用定时输出或高速输出,如第 5 步所述。
- 示例把工件视为一个点,较长或较宽的工件有前沿与后沿,需要调整被视为中心的位置。
- 编码器打滑或传送带打滑时,计数值会丢失,需要独立检查工件计数的传感器,以及发现队列不一致时的处置步骤,例如清空队列,并把途中的每个工件都剔除。
- 剔除闸口是真正会运动的设备。防护装置、紧急停止按钮和安全功能,与这套逻辑完全分开,并且在实际使用前,必须由具备机械安全资质的人员审查。
- 必须保留被丢弃结果、timeout 和 vision-down 的 log,以便事后查看。这些数字是时间预算变得紧张的预警信号。
应用到其他工作
三个假设示例,并非任何人的真实项目。
检查标签的装箱线
箱子通过标签相机,检查有没有批号和有效期限,吹气头在一米之外。从第 1 步开始:计算在产线最高速度下,相机最慢的检测时间够不够。如果不够,先移动吹气头,再去动逻辑。
分成多条通道的塑料件产线
检测结果不止通过与不通过,比如 A 级、B 级和废品。在队列条目中增加等级值,并设置多个闸口,每个闸口有自己的距离,每个条目与对应等级的闸口作出判定。用 key 配对的原则和默认值都不变。
相机位于外部电脑上的产线
当结果通过网络发送时,延迟的抖动比直接连接的智能相机更大。应在产线运行数小时期间测量实际延迟,在第 1 步中使用最差值而不是平均值,并用 heartbeat 来检查网络是否仍可使用。
常见错误
- 用到达的顺序把结果与工件配对。只要漏掉一次触发,此后的每个工件都对错了对象。
- 用计时器代替距离,然后传送带改变了速度。
- 不计算时间预算,却想用代码去解决本属机械方面的问题。
- 没有结果就放行,使得相机变慢或停止时,有缺陷的工件漏过去。
- 保留最近的重复结果而不是第一个结果,使得消息重复进来时,结果自己改变了。
- 用大于或小于来比较计数值,于是计数值回绕时系统崩溃,这可能发生在安装之后好几周。
- 在扫描时读取计数值,而不是用硬件锁存,数值会随扫描周期而偏差。
- 没有独立的工件计数器,因此不知道队列与实物不一致。
连接相机与 PLC 之前的检查清单
- 按最高速度和最差的相机时间计算时间预算,还留有余量吗
- 在传感器的信号沿处,用高速输入锁存编码器计数值
- 把 key 发给相机,并要求每一组结果都带着 key 返回
- 用 key 而不是顺序来配对结果,重复结果保留第一个,游离结果丢弃并记录
- 设置默认值为:在判定点之前没有结果就剔除
- 设置 heartbeat,以及相机沉默时的规则,并配有告警
- 用带符号的差值比较计数值,并测试跨越计数值回绕点的情况
- 以计数为单位测量脉冲宽度,并检查相邻的工件没有被一起吹掉
- 在闸口之前设置独立的工件计数传感器,用来与已判定的数量比较
- 测试最高速度、最紧挨的工件、迟到的结果、相机停止,以及产线继续运行,然后在使用前由具备机械安全资质的人员审查
注意:文中所有数字(速度、距离、相机时间、阀门时间)都是假设的,并非在真实机器上测得。ST 文件从未在真实 PLC 上运行,模拟环境的结果也不能保证您的机器会这样工作。必须用真实的传送带、相机和吹气头来测量和测试。
参考资料
- Cognex In-Sight — EtherNet/IP I/O module reference (Trigger, Trigger Ack, Results Valid, Inspection ID, Results Ack) (accessed 2026-11-21)
- Vision Systems Design — Cognex In-Sight bottle inspection (encoder reject tracking, failsafe reject) (accessed 2026-11-21)
- AC Automation — PLC example: shift register conveyor reject (accessed 2026-11-21)
- Industrial Monitor Direct — PLC sensor selection for conveyor reject stations (accessed 2026-11-21)
- Maple Systems — What is a high speed counter and how is it used with an encoder (accessed 2026-11-21)
- Wikipedia — Incremental encoder (quadrature counting, lost position) (accessed 2026-11-21)
- Wikipedia — Circular buffer (fixed-size FIFO, overflow behaviour) (accessed 2026-11-21)
- Wikipedia — IEC 61131-3 (PLC languages including Structured Text) (accessed 2026-11-21)




