Medium-speed logistics sorting line
This page is an IO sorting example: encoder counting plus digital inputs and outputs triggering the sorting flap. It is not a servo-synchronized axis and contains no CSP/CSV motion control.
Hardware configuration
- Master: Windows 10 × 1 + Intel i5 × 1
- Coupler: EK1100 × 1
- High-speed counter: EL5001 × 1
- Digital outputs: EL2008 × 1 (sorting flap control)
- Digital inputs: EL1008 × 1 (item detection sensor)
- Conveyor: variable-frequency drive × 1 + incremental encoder × 1
- Identification: industrial camera × 1 (selected to suit the application: barcode camera, line-scan camera, 3D camera)
Cost breakdown
| Category | Model/specification | Reference unit price (¥) | Qty | Subtotal (¥) |
|---|---|---|---|---|
| Coupler | EK1100 | 800 | 1 | 800 |
| High-speed counter | EL5001 | 1,200 | 1 | 1,200 |
| Digital outputs | EL2008 | 400 | 1 | 400 |
| Digital inputs | EL1008 | 350 | 1 | 350 |
| Variable-frequency drive | General-purpose 0.75~1.5 kW | 1,000 | 1 | 1,000 |
| Incremental encoder | 1000~2000 lines | 100 | 1 | 100 |
| Industrial camera | Barcode camera/other camera | 2,000~8,000 | 1 | 2,000~8,000 |
| Industrial PC | Intel i5 class | 3,000 | 1 | 3,000 |
| Whole-line reference total | ≈ ¥8,850~14,850 |
Performance figures
- Conveyor speed: 1~2 m/s (medium speed)
- Control cycle: 1 ms
- Sorting lanes: 8
Application scenario
A low-cost sorting line for small and medium logistics warehouses, chosen for its cost-effectiveness and typically used to sort regular items.
Conveyor speed 1~2 m/s. The encoder tracks the conveyor position in real time; the vision system identifies each parcel's barcode or appearance and then triggers the sorting flap by category to route the parcel automatically.
It also fits production-line quality rejection: the vision system detects a non-conforming part and triggers an IO rejection.
Code example
PDO struct definitions
using System.Runtime.InteropServices;
/// <summary>
/// EL5001 input PDO (0x1A00 channel 1: 1 byte status + 4 byte 32-bit counter value = 5 bytes)
/// This page frames by 0x1A00; if the device uses the standard mapping 0x1A01 (16-bit status + 32-bit counter value = 6 bytes),
/// The struct must become ushort Status, and CounterValue must stay at actual offset 2. The field order must match the real framing byte for byte.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct EL5001_Input
{
public byte Status; // Status byte (offset 0)
public int CounterValue; // 32-bit counter value (offset 1)
}
/// <summary>
/// EL1008 digital input PDO (8 inputs)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct EL1008_Input
{
public byte DigitalInputs; // 8-bit digital input status
}
/// <summary>
/// EL2008 digital output PDO (8 outputs)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct EL2008_Output
{
public byte DigitalOutputs; // 8-bit digital output control
}
Control code
using System;
using System.Threading;
using System.Collections.Generic;
using System.Collections.Concurrent;
using DarraEtherCAT_Master;
class SortingController
{
// Slave index (adjust to the actual topology; 0=EK1100, 1=EL5001, 2=EL2008, 3=EL1008)
const int SLAVE_EL5001 = 1; // High-speed counter
const int SLAVE_EL2008 = 2; // Digital output
const int SLAVE_EL1008 = 3; // Digital input
// ============ Configurable parameters (set externally) ============
/// <summary> Encoder pulse distance from each reject lane to the detection point (calibrated to the actual mechanical mounting) </summary>
public static int[] CylinderDistance { get; set; } = new int[]
{
3000, 5500, 8000, 10500, 13000, 15500, 18000, 20500
};
/// <summary> Output hold time of each reject-lane cylinder (ms) </summary>
public static int[] CylinderHoldMs { get; set; } = new int[]
{
200, 200, 200, 200, 250, 250, 300, 300
};
// ============ Task data structures ============
struct SortTask
{
public int TriggerPos; // Trigger the cylinder when this encoder position is reached
public int Channel; // Target reject lane (0-7)
}
struct ActiveCylinder
{
public int Channel; // Channel
public long OffTickMs; // Due time (Environment.TickCount64, monotonic milliseconds)
}
// ============ Three-level queue ============
//
// Vision thread ──EnqueueTask()──→ [_inbox] (thread-safe, enqueue only)
// │
// Main loop pulls one out every cycle ───────────→ [_pending] (in-flight material, waiting to reach the trigger position)
// │
// Encoder in position ────────────────→ [_active] (cylinder extended, waiting for the hold time to end)
// │
// Hold timeout ──────────────────→ clear, retract the cylinder
// 1. Queue buffer (written by the vision thread, read by the main loop)
static readonly ConcurrentQueue<SortTask> _inbox = new ConcurrentQueue<SortTask>();
// 2. In-flight material list (several items on the belt at once, each waiting for its own reject lane)
static readonly List<SortTask> _pending = new List<SortTask>();
// 3. Active cylinder list (several cylinders can act at once)
static readonly List<ActiveCylinder> _active = new List<ActiveCylinder>();
// Current encoder position (updated live by the main loop, readable from other threads)
public static volatile int CurrentEncoderPosition;
/// <summary>
/// Called by the external vision/barcode system: submit a reject task
/// Read the current encoder position automatically, add the distance to the target reject lane, and store it in the queue
/// </summary>
/// <param name="channel">target reject lane (0-7)</param>
public static void EnqueueTask(int channel)
{
if (channel < 0 || channel >= CylinderDistance.Length)
throw new ArgumentOutOfRangeException(nameof(channel), channel,
$"剔除口必须在 0~{CylinderDistance.Length - 1}"); // The reject lane must be within 0~{CylinderDistance.Length - 1}
_inbox.Enqueue(new SortTask
{
TriggerPos = CurrentEncoderPosition + CylinderDistance[channel],
Channel = channel
});
}
static void Main(string[] args)
{
// Build() returns a BuildResult (not the master itself); you must call .Master to get the master instance
var build = new DarraEtherCAT()
.SetENI("config.deni")
.Build();
if (!build.Success || build.Master == null)
{
Console.WriteLine($"主站初始化失败: {build.Message}"); // Master initialization failed: {build.Message}
return;
}
var master = build.Master;
try
{
// Cycle time: 1 ms. The encoder/IO snapshot is refreshed by the master at this rate; the polling loop only consumes the newest snapshot.
const uint CYCLE_NS = 1_000_000;
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;
}
// The state machine advances INIT → PREOP → SAFEOP → OP one level at a time, confirming each level and stopping on any failure;
// Do not treat "did not reach OP" as success and go on reading/writing the process image.
if (!master.SetState(EcState.PreOp))
{
Console.WriteLine("无法进入 PREOP"); // Failed to enter PREOP
return;
}
if (!master.SetState(EcState.SafeOp))
{
Console.WriteLine("无法进入 SAFEOP"); // Failed to enter SAFEOP
return;
}
if (!master.SetState(EcState.OP, out string opError))
{
Console.WriteLine($"无法进入 OP 状态: {opError}"); // Failed to enter the OP state: {opError}
return;
}
Console.WriteLine("物流分拣线启动!"); // Logistics sorting line started!
// Sensor edge detection (prevents repeated queuing while the signal stays high)
bool lastSensorState = false;
// The slave index follows a topology convention (0=EK1100, 1=EL5001, 2=EL2008, 3=EL1008);
// Stop immediately on a count mismatch, otherwise the data maps onto a different module.
if (master.SlaveCount < 4)
{
Console.WriteLine($"从站数量不足: 实际 {master.SlaveCount}, 需要 4 个 (EK1100/EL5001/EL2008/EL1008)"); // Not enough slaves: {master.SlaveCount} found, 4 needed (EK1100/EL5001/EL2008/EL1008)
return;
}
// Map the PDO once (the reference points into the process image, which the master loop keeps up to date)
ref readonly var counter = ref master.Slaves[SLAVE_EL5001].PDO.InputsMapping<EL5001_Input>();
ref readonly var input = ref master.Slaves[SLAVE_EL1008].PDO.InputsMapping<EL1008_Input>();
ref var output = ref master.Slaves[SLAVE_EL2008].PDO.OutputsMapping<EL2008_Output>();
while (true)
{
long now = Environment.TickCount64; // Monotonic milliseconds; do not use DateTime.Now (system clock corrections jump)
// 1. Read the encoder position
CurrentEncoderPosition = counter.CounterValue;
// 2. Item detection sensor - rising-edge triggered
bool sensorHigh = (input.DigitalInputs & 0x01) != 0;
if (sensorHigh && !lastSensorState)
{
// New material detected, at which point the vision system should call EnqueueTask(channel)
// If no vision system is connected, queue the default channel directly here:
// EnqueueTask(0);
}
lastSensorState = sensorHigh;
// 3. Pull new tasks from the inbox -> add to pending (the in-flight material list)
while (_inbox.TryDequeue(out var task))
_pending.Add(task);
// 4. Scan the in-flight material: encoder reaches the trigger position -> activate the cylinder
for (int i = _pending.Count - 1; i >= 0; i--)
{
if (CurrentEncoderPosition >= _pending[i].TriggerPos)
{
_active.Add(new ActiveCylinder
{
Channel = _pending[i].Channel,
OffTickMs = now + CylinderHoldMs[_pending[i].Channel]
});
_pending.RemoveAt(i);
}
}
// 5. Combine the output bits: OR together all active cylinders, removing any that timed out
byte outputBits = 0;
for (int i = _active.Count - 1; i >= 0; i--)
{
if (now < _active[i].OffTickMs)
outputBits |= (byte)(1 << _active[i].Channel);
else
_active.RemoveAt(i); // Hold time elapsed, retract the cylinder
}
output.DigitalOutputs = outputBits;
Thread.Sleep(1); // IO polling tick (best-effort, not a motion cycle); the snapshot refreshes on LoopCycle=1 ms
}
}
finally
{
master.Dispose();
}
}
}
The trigger test CurrentEncoderPosition >= TriggerPos assumes that the encoder counts in the same direction as the item flow (increasing downstream). With the encoder mounted in reverse, change the test to <=, or correct the direction bit or the wiring at power-up.
A 32-bit counter wraps on a long line (about ±2.1 km of travel at 1000 pulses/mm); beyond that range, expand the difference into a signed value before comparing.
When a slave drops out of OP, its PDO snapshot stops updating and this loop keeps reading the last value. Production code should run a low-frequency diagnostic thread that checks slave.State and raises an alarm; do not poll the state on every pass of the polling loop.
Complete example code
This page describes a scenario; there is no standalone project that corresponds one-to-one to "encoder + digital IO sorting". Runnable reference project:
- Panasonic_ConveyorSync — conveyor master/slave synchronization + item tracking + sensor triggering, the closest match to the conveyor sorting usage on this page (that project synchronizes the conveyor with a servo and does not include the digital-only flap logic of this page).
The IO pattern on this page (read PDO.InputsMapping<T>(), write PDO.OutputsMapping<T>(); the process image is refreshed by the bus cycle) applies directly; compose the flap outputs with 1 << channel and write the result back as one byte.