Ultra-high-speed intelligent sorting machine
This page is an IO-triggered sorting example: encoder position comparison plus valve-group output. It is not a synchronized servo axis and has no CSP/CSV motion control.
Hardware configuration
- Master: Windows 10 IoT × 1 + Intel 13600K × 1 + RTX4060 × 1
- Couplers: EK1100 coupler × 1 + EL5001 high-speed counter × 1 + EL1008 digital input × 1
- Output module: custom Infineon XMC4800 EtherCAT slave, 128 digital outputs × 1 (solenoid valve manifold)
- Conveyor: frequency converter × 1 + encoder × 1
- Recognition system: Hikvision MV-CL042-91GC line-scan camera × 2 + RTX4060 inference
Cost breakdown
| Category | Model/specification | Reference unit price (¥) | Quantity | Subtotal (¥) |
|---|---|---|---|---|
| Coupler | EK1100 | 800 | 1 | 800 |
| High-speed counter | EL5001 | 1,200 | 1 | 1,200 |
| Digital input | EL1008 | 350 | 1 | 350 |
| Output module | Custom XMC4800, 128 IO outputs | 1,000 | 1 | 1,000 |
| Frequency converter | 1,500 | 1 | 1,500 | |
| Encoder | 100 | 1 | 100 | |
| Line-scan camera | Hikvision MV-CL042-91GC | 2,200 | 2 | 4,400 |
| GPU | RTX4060 | 2,500 | 1 | 2,500 |
| Industrial PC | Intel 13600K class | 4,000 | 1 | 4,000 |
| Total reference for the line | ≈ ¥15,850 |
The prices above are reference prices for the core components (RMB) and exclude the solenoid valve manifold, cables, frame and similar items.
Performance figures
- Conveyor speed: 5 m/s
- Recognition accuracy: ≥99.5%
- IO decision latency: ≤50 µs (the custom IO control driver compares in memory, excluding bus transfer)
- Ejection timing resolution: = EtherCAT bus cycle (500 µs in this case; 2.5 mm per cycle at 5 m/s)
Application scenario
Intelligent sorting lines for agricultural products, recyclables and minerals. A 5 m/s conveyor with 128 solenoid nozzles: the camera returns an image, which triggers AI recognition, and a blow task is submitted. The IO control driver compares the encoder against the trigger position in memory on every cycle (decision latency ≤50 µs); the resolution of the actual ejection instant is set by the EtherCAT bus cycle — with a 500 µs cycle at 5 m/s the belt advances 2.5 mm per cycle, so the trigger algorithm must compensate for this quantization step; the 50 µs decision latency must not be treated as 50 µs execution accuracy. Camera callbacks (application layer) and IO timing control (driver layer) are decoupled.
Code description
System architecture
Key design:
The main program obtains the PDO buffer address from the EtherCAT driver and passes it directly to the IO control driver. The IO control driver reads and writes PDO memory directly, and the EtherCAT driver sends and receives every cycle automatically, with no intermediate copy.
Key timing logic:
- PDO buffer shared directly — the main program passes the encoder input PDO address and the 128-channel output PDO address to the IO control driver; the two drivers use the same memory
- Trigger position calculation — after the camera returns an image and AI recognition completes,
检测时编码器 + 相机到喷嘴距离= trigger encoder value - Trigger on position comparison — the IO control driver reads the encoder directly from the PDO and writes the PDO output directly on
≥ 触发位置 - Pulse closes automatically — the close instant is recorded for each channel and the IO control driver resets it automatically
The AI recognition models in this case (object detection, material classification and so on), together with the line-scan camera calibration and image stitching algorithms, are not included in the EtherCAT master software license.
The high-precision IO control in the driver layer, the custom XMC4800 128-channel IO output module and the related hardware and low-level timing logic are not included in the EtherCAT master software license.
Code example
PDO struct
using System.Runtime.InteropServices;
/// <summary>
/// EL5001 high-speed counter input PDO (1 byte status + 4 byte 32-bit counter value = 5 bytes)
/// The field order must match the ESI default mapping byte for byte; CounterValue sits at offset = 1 byte.
/// The count value is UDINT; here it is read as int over the same 4 bytes. Continuous running wraps past 2^31,
/// For long continuous production runs, compare an unsigned difference to decide "has it arrived" instead of comparing magnitudes directly.
/// If the mapping in config.deni is not this set (it may map Latch and others too), the struct must be rearranged to match the actual entries.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SensorInput
{
public byte Status; // 0x6000:01 status (offset 0)
public int CounterValue; // 0x6000:02 counter value UDINT (offset 1)
}
The 128 outputs of the custom XMC4800 are accessed as raw bytes (OutputsPtr cast to byte*); no struct layout is assumed.
Main program
using System;
using System.Runtime.InteropServices;
using System.Threading;
using DarraEtherCAT_Master;
/// <summary>
/// Main program - start the EtherCAT driver, get the process image address, pass it to the IO control driver
/// </summary>
class SortingMain
{
// Slave index (hardware list order: 0=EK1100, 1=EL5001, 2=EL1008, 3=XMC4800 output)
// Must match the actual DENI; a misaligned index maps to a different module (a struct size mismatch throws "结构体大于输入 PDO" (SDK output, = struct larger than input PDO)).
const int SLAVE_ENCODER = 1;
const int SLAVE_ACTUATOR = 3;
const uint CYCLE_NS = 500_000; // Bus cycle 500 µs; the jet timing resolution equals this cycle
static unsafe void Main(string[] args)
{
// 1. Start the EtherCAT driver
// Build() returns a BuildResult (not the master itself): the failure reason is in Message, on success take the master instance from Master
var build = new DarraEtherCAT()
.SetENI("config.deni")
.SetNetwork("以太网") // Ethernet
.Build();
if (!build.Success || build.Master == null)
{
Console.WriteLine($"主站初始化失败: {build.Message}"); // Master initialization failed: {build.Message}
return;
}
var master = build.Master;
// The IO control driver and its thread are torn down in finally: stop the consumer thread first, then release the master
SortingIOController ioCtrl = null;
Thread ioThread = null;
try
{
// The slave table must hold at least 4 entries (0=EK1100, 1=EL5001, 2=EL1008, 3=XMC4800), otherwise the indices below go out of range
if (master.SlaveCount <= SLAVE_ACTUATOR)
{
Console.WriteLine($"从站不足: 需要至少 {SLAVE_ACTUATOR + 1} 个, 实际 {master.SlaveCount}"); // Not enough slaves: at least {SLAVE_ACTUATOR + 1} needed, {master.SlaveCount} found
return;
}
// Set the cycle time first and read it back to verify - the bus cycle sets the resolution of the jet timing
master.LoopCycle = CYCLE_NS;
if (master.LoopCycle != CYCLE_NS)
{
Console.WriteLine($"LoopCycle 读回 {master.LoopCycle}ns ≠ {CYCLE_NS}ns, 拒绝启动"); // LoopCycle read back {master.LoopCycle}ns ≠ {CYCLE_NS}ns, refusing to start
return;
}
if (!master.SetState(EcState.OP, out string opError))
{
Console.WriteLine($"无法进入 OP: {opError}"); // Failed to enter OP: {opError}
return;
}
// 2. Get the process image address - both drivers share it directly, no copy in between.
// InputsPtr / OutputsPtr are the SDK's public process image pointers, valid until Close / re-mapping.
// Do not write fixed (&InputsMapping<T>()): that takes the address of a ref readonly return value, and fixed is only meant for managed objects.
IntPtr encoderPtr = master.Slaves[SLAVE_ENCODER].InputsPtr; // EL5001 input (written by the EtherCAT driver, read by IO control)
IntPtr actuatorPtr = master.Slaves[SLAVE_ACTUATOR].OutputsPtr; // XMC4800 128-channel output (written by IO control, sent by the EtherCAT driver)
// 3. Start the IO control driver (pass the process image pointer for direct read/write)
ioCtrl = new SortingIOController((SensorInput*)encoderPtr, (byte*)actuatorPtr);
ioThread = new Thread(ioCtrl.Run) { IsBackground = true, Priority = ThreadPriority.Highest };
ioThread.Start();
// 4. Register the camera callback - the camera thread never writes the PDO, it only submits tasks; the encoder is read from the process image with Marshal
// (IntPtr can be captured by a lambda; pointer locals cannot)
// camera.OnImageReceived += (image) =>
// {
// var targets = aiModel.Detect(image);
// int encoder = Marshal.ReadInt32(encoderPtr, 1); // SensorInput.CounterValue offset = 1 byte (Pack = 1)
// foreach (var t in targets)
// {
// int startChannel = t.PixelStart * 128 / cameraPixelCount;
// int channelCount = Math.Max(1, t.PixelWidth * 128 / cameraPixelCount);
// int triggerEncoder = encoder + cameraToNozzle;
// ioCtrl.Submit(triggerEncoder, startChannel, channelCount);
// }
// };
Console.WriteLine("分拣系统启动, 按 Enter 退出"); // Sorting system started, press Enter to exit
Console.ReadLine();
}
finally
{
// Exit order: stop the IO thread first, then release the master.
// Dispose releases the process image (InputsPtr / OutputsPtr become invalid immediately); doing it the other way round lets the IO thread read freed memory.
if (ioCtrl != null) ioCtrl.Stop();
if (ioThread != null) ioThread.Join(1000);
master.Dispose();
}
}
}
SortingIOController is a custom IO control driver wrapper for this case and is not part of the EtherCAT master SDK; the SDK only provides InputsPtr / OutputsPtr and InputsMapping / OutputsMapping (the pointers are on Slave, not on slave.PDO). A process image pointer is valid until Close or a remap: slave.ProcessImageGeneration changes when the process image is replaced, so a consumer thread must fetch the pointer again by generation and must not cache it across generations; on exit, stop the consumer thread first, then call master.Dispose(). The example reads the process image directly through pointers, so the project must enable AllowUnsafeBlocks.
Sorting task struct
/// <summary>
/// Sorting task - submitted by the vision system, consumed by the IO control driver
/// </summary>
public struct SortingTask
{
public int TriggerEncoder; // Blow-off position (absolute encoder value, triggers on arrival)
public int StartChannel; // Start channel (mapped from the pixel start point, 0-127)
public int ChannelCount; // Channel width (mapped from the pixel width)
}
Example of enqueuing from the camera callback:
// Camera image event -> AI recognition -> compute the blow-off position -> submit to the IO control driver
// The IO control driver reads the encoder straight from the process image and writes the PDO outputs directly on arrival
// (encoderPtr is an IntPtr, not a pointer local; lambdas cannot capture pointer locals)
camera.OnImageReceived += (image) =>
{
var targets = aiModel.Detect(image); // AI batch recognition
int encoder = System.Runtime.InteropServices.Marshal.ReadInt32(encoderPtr, 1); // CounterValue offset = 1 byte
foreach (var t in targets)
{
// Pixel -> channel mapping (128 channels cover the camera field of view)
int startChannel = t.PixelStart * 128 / cameraPixelCount;
int channelCount = Math.Max(1, t.PixelWidth * 128 / cameraPixelCount);
// Blow-off position = encoder at detection + camera-to-nozzle distance (encoder pulses)
int triggerEncoder = encoder + cameraToNozzle;
ioCtrl.Submit(triggerEncoder, startChannel, channelCount);
}
};
Complete example code
This page describes a scenario. For runnable reference see FurutaPendulum (a compilable project with a non-servo counter IO module and a 500 µs cyclic callback that reads the process image; remove the pendulum-arm servo and fit a 128-channel valve manifold output module to reuse it) and HCFA_X3E_QuarterTurn (a single-axis reference with real PDO mapping and outputs issued every cycle). Encoder position comparison triggering, valve pulse timing and the custom XMC4800 128-channel output module are specific to this page's scenario; the reference projects contain no equivalent implementation.