6 delta robots collaborative sorting
This page is a multi-axis synchronization example: 18 axes across 6 robots are advanced by the same Process Data Object (PDO) cyclic callback and the same time base, not by independent per-axis PP jogging.
The master side handles CSP target output, the CiA 402 control word handshake driven by the status word, Distributed Clocks (DC) synchronization, and per-axis fault and dropout detection (slave.IsLost, master Events.SlaveOffline / SlaveOnline): if a single slave drops out, the master only raises an alarm and removes that axis from the coordinated motion, while the cycles of the other axes continue. Delta kinematics, vision recognition and multi-robot scheduling belong to the application layer.
Hardware configuration
- Master: Windows 10 IoT × 1 + Intel 13600KF × 1 + RTX4060 × 1
- Coupler: EK1100 × 1 + EL5001 high-speed counter × 1 + EL1008 digital input × 1
- Conveyor: VFD × 1 + incremental encoder × 1
- Height measurement: laser distance sensor × 6 (mounted above the suction cup)
- Recognition system: line-scan camera × 1 (encoder-triggered, GigE) + line light source × 1 + RTX4060 inference
- Delta robots: 86 closed-loop integrated stepper × 18 (NEMA34, 12 N.m, EtherCAT bus, 36–60 V) + suction cup × 6
Motor built-in I/O assignment
| I/O | Function | Description |
|---|---|---|
| DI1 | Positive limit | Joint positive-direction limit switch |
| DI2 | Negative limit | Joint negative-direction limit switch |
| DI3 | Home | Homing sensor |
| DI4 | Laser distance signal | Wired on the Joint 0 motor only (part detection) |
| DI5 | Reserved | |
| DO1 | Suction cup control | Used by the Joint 0 motor only (solenoid valve) |
| DO2 | Reserved |
Each robot has 3 motors. Only the Joint 0 motor has DO1 wired to the suction cup solenoid valve and DI4 wired to the laser sensor; DO and DI4–5 on the other motors are unused. Suction cup control goes directly through the motor built-in DO.
Cost analysis
| Category | Model/specification | Reference unit price (¥) | Qty | Subtotal (¥) |
|---|---|---|---|---|
| Coupler | EK1100 | 800 | 1 | 800 |
| High-speed counter | EL5001 | 1,000 | 1 | 1,000 |
| Digital input | EL1008 | 300 | 1 | 300 |
| VFD | - | 800 | 1 | 800 |
| Encoder | - | 100 | 1 | 100 |
| Laser distance | - | 150 | 6 | 900 |
| Integrated closed-loop stepper | Lichuan 86 closed-loop 12 N.m | 540 | 18 | 9,720 |
| Line-scan camera | GigE line-scan + line light source | 3,000 | 1 | 3,000 |
| GPU | RTX4060 | 2,200 | 1 | 2,200 |
| Industrial PC | Intel 13600KF class | 4,000 | 1 | 4,000 |
| Whole-line reference total | ≈ ¥23,000 |
Reference prices for the core components (RMB). The robot frame structure, conveyor structure, cabling and similar items are not included.
Performance figures
| Metric | Value | Notes |
|---|---|---|
| Conveyor speed | 1.5 m/s | |
| Sorting accuracy | ±2 mm | |
| Sorting cycle | ≤1.5 s/piece/station | Includes pick + place + return |
| Line throughput | ≈14,400 pieces/hour | 6 stations in parallel |
| EtherCAT cycle | 500 µs | Value used in this example; adjust to the takt requirement (LoopCycle, ns) |
| Motor holding torque | 12 N.m | |
| Motor voltage | 48 VDC |
Application scenario
Food and electronic component sorting
A high-speed sorting line for food and electronic components. 6 delta robots are arranged along the conveyor; after AI vision recognition, the master assigns the pick tasks centrally. Line throughput is about 14,400 pieces/hour.
Mixed plastic sorting in recycling
In a waste plastic recycling line, mixed plastic is shredded and passes the conveyor at high speed. A line-scan camera combined with an AI model identifies the plastic type in real time, and the delta robots sort it by material into the matching bins.
The AI recognition models in this case (object detection, plastic material classification and so on), as well as line-scan camera calibration and image stitching algorithms, are not included in the EtherCAT master software license.
Motion control algorithms such as the inverse kinematics and trajectory planning of the delta robots are not included in the EtherCAT master software license.
Code description
System architecture
Key design points:
- Camera AI enqueues targets — after recognition, the vision callback writes the target coordinates and encoder position into the shared queue
- Robots claim targets on their own — the 6 robot threads are independent; when idle, each claims the nearest target from the queue
- Line tracking during the pick — during the pick phase (including the hold segment while vacuum builds), the single PDO callback reads the encoder every cycle, recomputes the target X offset and compensates conveyor motion
- Automatic removal out of range — the main loop periodically removes targets whose travel distance exceeds the total conveyor length (
ConveyorLength), treating them as dropped - Fixed absolute positions — each robot has a fixed absolute coordinate along the conveyor and only picks targets inside its working radius
- Motor DO drives the suction cup — DO1 of the Joint 0 motor drives the suction cup solenoid valve directly, with no external I/O module
- 18-axis synchronized CSP output — the joint targets are computed by the same PDO callback from the same time base and submitted in the same frame; PP is not used to resend targets every cycle
Code example
PDO struct definitions
using System.Runtime.InteropServices;
/// <summary>
/// Input PDO (TxPDO 0x1A00)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct StepperMotor_Input
{
public ushort ErrorCode; // 0x603F error code
public ushort StatusWord; // 0x6041 status word
public int ActualPosition; // 0x6064 actual position
public uint DigitalInputs; // 0x60FD digital inputs (bit0=DI1 ~ bit4=DI5)
public int ActualVelocity; // 0x606C actual velocity
public int FollowError; // 0x60F4 following error
public ushort TouchProbeStatus; // 0x60B9 probe status
public int TouchProbePos1Positive; // 0x60BA probe 1 positive-edge position
public int TouchProbePos1Negative; // 0x60BB probe 1 negative-edge position
public int TouchProbePos2Positive; // 0x60BC probe 2 positive-edge position
public int TouchProbePos2Negative; // 0x60BD probe 2 negative-edge position
public sbyte ModesOfOperationDisplay; // 0x6061 current mode of operation
}
/// <summary>
/// Output PDO (RxPDO 0x1600)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct StepperMotor_Output
{
public ushort ControlWord; // 0x6040 control word
public int TargetPosition; // 0x607A target position
public int TargetVelocity; // 0x60FF target velocity
public ushort TouchProbeFunction; // 0x60B8 probe function
public uint DigitalOutputs; // 0x60FE:01 digital outputs (bit0=DO1, bit1=DO2)
}
/// <summary>
/// EL5001 high-speed counter input PDO (0x1A00 channel 1: 1 byte status + 4 byte 32-bit counter value = 5 bytes)
/// The field order must match the ESI default mapping byte for byte: Status at offset 0, CounterValue at offset 1.
/// 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
/// ...and check the total byte count. A struct larger than the actual input PDO, or fields out of place, throws "结构体大于输入 PDO" (SDK output, = struct larger than input PDO) or reads wrong values.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct EL5001_Input
{
public byte Status; // 0x6000:01 status (offset 0)
public int CounterValue; // 0x6000:02 counter value UDINT (offset 1), read as int over the same 4 bytes
}
/// <summary>
/// Sorting target data - created and queued by the vision system
/// </summary>
public class SortingTarget
{
public int Id { get; set; }
public int EncoderAtDetect { get; set; } // Encoder position at detection (pulses)
public int PixelY { get; set; } // Vertical conveyor direction offset (pixels, camera coordinates)
public int Category { get; set; } // AI classification result
public int AssignedRobot { get; set; } // -1=unassigned, >=0=taken over
}
Control code
using System;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using DarraEtherCAT_Master;
/// <summary>
/// Delta sorting EtherCAT controller
/// Responsibility: 18-axis CSP synchronised motion, CiA402 state machine, DO suction cup control
/// Vision AI queuing, inverse kinematics, laser ranging and the like are implemented by external services
/// </summary>
class DeltaSortingController
{
const int ROBOT_COUNT = 6;
const int AXES_PER_ROBOT = 3;
// Bus cycle (ns): default 500 µs; set it and read it back to verify before any state transition
const uint CYCLE_NS = 500_000;
const sbyte MODE_CSP = 8; // 0x6060 = 8, cyclic synchronous position
// In-position criterion (pulses) / line-tracking descent duration (seconds) / settling window after the time base runs out (seconds)
const int ARRIVE_TOLERANCE = 10;
const double TRACK_DESCEND_SECONDS = 0.18; // Must complete while the target is crossing the working radius window: 2x3000/22500 ~= 0.27 s
const double SETTLE_SECONDS = 0.05;
// Hold time while the suction cup builds vacuum (seconds): it must keep tracking the belt during this time, otherwise the workpiece is carried away
const double SUCTION_SETTLE_SECONDS = 0.05;
// 0x60F4 following error limit (pulses): exceeding it means a crash or lost steps, so abort immediately
const int MaxFollowingErrorPulses = 5000;
// Trapezoidal velocity profile: acceleration/deceleration each take this share of the total duration (peak velocity = joint max velocity)
const double ACCEL_TIME_FRACTION = 0.2;
/// <summary>Joint max speed (pulses/s), tuned for the mechanics; used to derive the motion duration from the travel</summary>
static readonly int[] JointMaxSpeedPps = { 200000, 200000, 200000 };
// Slave index (index into the master.Slaves list, from 0; hardware list order: 0=EK1100, 1=EL5001, 2=EL1008, 3~20=18 motors)
// Must match the topology of the actual config.deni; a misaligned index maps to a different module
const int SLAVE_EL5001 = 1; // Encoder
const int SLAVE_MOTOR_BASE = 3; // Stepper motor start (3~20)
// Built-in motor I/O bit definitions
const uint DI_LASER = 0x08; // DI4: laser ranging (J0 only)
const uint DO_SUCTION = 0x01; // DO1: suction cup solenoid valve (J0 only)
// ============ Configurable parameters (all conveyor distances are encoder pulse values) ============
// Encoder 3000 pulses/rev, 200 mm belt pulley circumference -> 15000 pulses/metre
/// <summary> Distance from the camera to robot 1 (encoder pulses) </summary>
public int CameraToFirstRobot { get; set; } = 22500; // ≈1.5m
/// <summary> Robot spacing (encoder pulses), 6 units evenly spaced </summary>
public int RobotSpacing { get; set; } = 15000; // 1m
/// <summary> Robot working radius (encoder pulses); a target must be within this range to be picked </summary>
public int WorkRadius { get; set; } = 3000; // ≈0.2m
/// <summary> Total conveyor length (encoder pulses); targets beyond this distance are rejected automatically </summary>
public int ConveyorLength { get; set; } = 120000; // ≈8m
/// <summary> Get the robot's absolute position (encoder pulses) </summary>
int GetRobotPosition(int robotId) => CameraToFirstRobot + robotId * RobotSpacing;
// ============ Shared target queue ============
readonly List<SortingTarget> targetList = new List<SortingTarget>();
readonly object listLock = new object();
/// <summary>
/// The vision system calls this method to queue its recognition results
/// </summary>
public void EnqueueTarget(SortingTarget target)
{
target.AssignedRobot = -1;
lock (listLock) { targetList.Add(target); }
}
// Robot state
bool[] robotBusy = new bool[ROBOT_COUNT];
readonly bool[] robotFaulted = new bool[ROBOT_COUNT]; // Transport failed and the workpiece is still on the suction cup: this station stops taking orders
DarraEtherCAT master;
// ============ Motion command state (the robot thread only writes requests, the PDO callback computes the targets) ============
enum MoveKind { Idle, Move, TrackDescend, TrackHold }
class RobotMotion
{
public MoveKind Kind;
public readonly int[] StartPulses = new int[AXES_PER_ROBOT];
public readonly int[] EndPulses = new int[AXES_PER_ROBOT];
public int TrackTargetEncoder; // Line tracking: encoder position at detection
public int TrackPixelY; // Line tracking: camera Y offset
public int TrackRobotPos; // Line tracking: robot absolute position
public long StartTs;
public double DurationSeconds;
public volatile bool Aborted;
public readonly ManualResetEventSlim Completed = new ManualResetEventSlim(false);
}
readonly RobotMotion[] motions = Enumerable.Range(0, ROBOT_COUNT)
.Select(_ => new RobotMotion()).ToArray();
readonly bool[] faultResetRequested = new bool[ROBOT_COUNT * AXES_PER_ROBOT];
readonly byte[] faultResetPhase = new byte[ROBOT_COUNT * AXES_PER_ROBOT]; // 0=next tick is the low phase, 1=next tick is the high phase
// Suction cup request (1=open, 0=close): the robot thread only registers the request, the actual 0x60FE:01 is written by the PDO callback,
// Committed in the same PDO frame as 0x6040 / 0x607A, so a non-real-time thread changing the process image cannot lose an update
readonly int[] suctionRequested = new int[ROBOT_COUNT];
volatile bool pdoFaulted;
volatile bool servoEnable; // Master enabling switch: when false always 0x0006 + target = actual, never auto-enable
// ============ Main flow ============
static int GetMotorSlaveIndex(int robotId, int joint)
=> SLAVE_MOTOR_BASE + robotId * AXES_PER_ROBOT + joint;
/// <summary>
/// Read the current encoder value (pulses)
/// </summary>
int GetEncoder()
{
ref readonly var enc = ref master.Slaves[SLAVE_EL5001].PDO.InputsMapping<EL5001_Input>();
return enc.CounterValue;
}
void Run()
{
// config.deni must be exported by the master GUI after scanning the real slaves; do not edit it by hand
// 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")
.Build();
if (!build.Success || build.Master == null)
{
Console.WriteLine($"主站初始化失败: {build.Message}"); // Master initialization failed: {build.Message}
return;
}
master = build.Master;
try
{
// The slave table must hold at least 21 entries (coupler + encoder + DI + 18 motors), otherwise the indices below go out of range
int requiredSlaves = SLAVE_MOTOR_BASE + ROBOT_COUNT * AXES_PER_ROBOT;
if (master.SlaveCount < requiredSlaves)
{
Console.WriteLine($"从站不足: 需要 {requiredSlaves} 个, 实际 {master.SlaveCount}"); // Not enough slaves: {requiredSlaves} needed, {master.SlaveCount} found
return;
}
// Cycle time: set it and read it back to verify before any state transition (the pacing reference for 18-axis interpolation)
master.LoopCycle = CYCLE_NS;
if (master.LoopCycle != CYCLE_NS)
{
Console.WriteLine($"LoopCycle 设定失败: 请求 {CYCLE_NS}ns, 读回 {master.LoopCycle}ns"); // LoopCycle setup failed: {CYCLE_NS}ns requested, {master.LoopCycle}ns read back
return;
}
// PreOp: 18 axes all in CSP + DC Sync0 = the same cycle
// This PDO mapping has no mode word, so 0x6060 must be set to 8 over SDO in PreOp and read back to verify
if (!master.SetState(EcState.PreOp, out string preMsg))
{ Console.WriteLine($"无法进入 PreOp: {preMsg}"); return; } // Failed to enter PreOp: {preMsg}
for (int r = 0; r < ROBOT_COUNT; r++)
{
for (int j = 0; j < AXES_PER_ROBOT; j++)
{
int idx = GetMotorSlaveIndex(r, j);
var slave = master.Slaves[idx];
if (!SetCspMode(slave, 0x6060))
{
Console.WriteLine($"从站 {idx} CSP 模式设定失败"); // Slave {idx} failed to set CSP mode
return;
}
// 18 axes must share one Sync0 time base: refuse to enter the motion chain if there is no DC capability or the configuration fails
if (!slave.HasDC || !slave.ConfigureDC(CYCLE_NS))
{
Console.WriteLine($"从站 {idx} 无 DC 能力或 DC Sync0({CYCLE_NS}ns) 配置失败, 拒绝进入运动链路"); // Slave {idx} has no DC capability or DC Sync0({CYCLE_NS}ns) configuration failed, refusing to enter the motion link
return;
}
}
}
// SafeOp: write a safety frame per axis before entering OP - target = actual, control word = Shutdown, so nothing jumps
if (!master.SetState(EcState.SafeOp, out string safeMsg))
{ Console.WriteLine($"无法进入 SafeOp: {safeMsg}"); return; } // Failed to enter SafeOp: {safeMsg}
for (int r = 0; r < ROBOT_COUNT; r++)
{
for (int j = 0; j < AXES_PER_ROBOT; j++)
{
ref var o = ref master.Slaves[GetMotorSlaveIndex(r, j)].PDO.OutputsMapping<StepperMotor_Output>();
ref readonly var i = ref master.Slaves[GetMotorSlaveIndex(r, j)].PDO.InputsMapping<StepperMotor_Input>();
o.ControlWord = 0x0006;
o.TargetPosition = i.ActualPosition;
o.DigitalOutputs = 0;
}
}
// After entering OP, attach the single PDO cycle callback: the 18 axis targets and the CiA402 control word are all written here
if (!master.SetState(EcState.OP, out string opMsg))
{ Console.WriteLine($"无法进入 OP: {opMsg}"); return; } // Failed to enter OP: {opMsg}
master.Events.ProcessDataCyclicSync += OnPdoCycle;
if (!InitializeMotors()) { Console.WriteLine("电机未全部使能, 拒绝运行"); return; } // Not all motors are enabled, refusing to run
// Start 6 robot threads, each claiming targets from the queue independently (task orchestration only, no PDO writes)
for (int i = 0; i < ROBOT_COUNT; i++)
{
int id = i;
new Thread(() => RobotLoop(id)) { IsBackground = true }.Start();
}
Console.WriteLine($"系统启动: {ROBOT_COUNT} 台机器人, 间距 {RobotSpacing} 脉冲, 工作半径 {WorkRadius} 脉冲"); // System started: {ROBOT_COUNT} robots, spacing {RobotSpacing} pulses, working radius {WorkRadius} pulses
// Main loop: periodically clean up over-distance targets
while (true)
{
PurgeExpiredTargets();
Thread.Sleep(50);
}
}
finally
{
try { master.Events.ProcessDataCyclicSync -= OnPdoCycle; }
catch (Exception ex)
{
Console.WriteLine($"退订 PDO 周期回调失败: {ex.GetType().Name}: {ex.Message}"); // Failed to unsubscribe from the PDO cyclic callback: {ex.GetType().Name}: {ex.Message}
}
master.Dispose();
}
}
/// <summary>
/// Wait for all 18 axes to reach OperationEnabled
/// The handshake itself is advanced by OnPdoCycle from the status word (0x06 -> 0x07 -> 0x0F, fault reset 0x0006 -> 0x0086); this call just waits for the result;
/// While disabled or handshaking, the target position always equals the actual position.
/// </summary>
bool InitializeMotors()
{
servoEnable = true; // Explicit enable action: until then the callback always sends 0x0006 and never auto-enables
int total = ROBOT_COUNT * AXES_PER_ROBOT;
int enabled = 0;
int fault = 0;
var deadline = Stopwatch.GetTimestamp() + (long)(5.0 * Stopwatch.Frequency);
while (Stopwatch.GetTimestamp() < deadline)
{
enabled = 0;
fault = 0;
for (int r = 0; r < ROBOT_COUNT; r++)
{
for (int j = 0; j < AXES_PER_ROBOT; j++)
{
ref readonly var i = ref master.Slaves[GetMotorSlaveIndex(r, j)].PDO.InputsMapping<StepperMotor_Input>();
if ((i.StatusWord & 0x6F) == 0x27) enabled++;
else if ((i.StatusWord & 0x4F) == 0x08) fault++;
}
}
if (enabled == total)
{
Console.WriteLine($"已使能 {total} 台电机 (CSP)"); // {total} motors enabled (CSP)
return true;
}
if (fault > 0)
{
Console.WriteLine($"{fault} 台电机处于故障态, 需人工确认后调用 ResetAllFaults()"); // {fault} motors are in the fault state, manual confirmation is required before calling ResetAllFaults()
return false;
}
Thread.Sleep(10);
}
Console.WriteLine($"使能超时: 仅 {enabled}/{total} 台进入 OperationEnabled"); // Enable timeout: only {enabled}/{total} reached OperationEnabled
return false;
}
/// <summary>
/// Fault reset request (call only after manual confirmation)
/// Only set the request on axes genuinely in Fault ((sw & 0x4F)==0x08); healthy axes are left alone - sending to a healthy axis
/// 0x0006->0x0086 first switches it off (T8) and then performs one illegal transition.
/// The callback creates a rising edge on bit7 over two cycles: 0x0006 (low phase) -> 0x0086 (high phase).
/// </summary>
void ResetAllFaults()
{
int n = 0;
for (int r = 0; r < ROBOT_COUNT; r++)
{
for (int j = 0; j < AXES_PER_ROBOT; j++)
{
int ai = r * AXES_PER_ROBOT + j;
ref readonly var i = ref master.Slaves[GetMotorSlaveIndex(r, j)]
.PDO.InputsMapping<StepperMotor_Input>();
bool fault = (i.StatusWord & 0x4F) == 0x08;
faultResetPhase[ai] = 0;
faultResetRequested[ai] = fault;
if (fault) n++;
}
}
Console.WriteLine(n > 0 ? $"已请求复位 {n} 个 Fault 轴" : "没有处于 Fault 的轴, 复位请求忽略"); // Reset requested for {n} faulted axes (or: no axis is in Fault, so the reset request is ignored)
}
// ============ Robot thread ============
/// <summary>
/// Robot control loop - when idle, claim the nearest target from the shared queue
/// </summary>
void RobotLoop(int robotId)
{
while (true)
{
// Transport failed and the workpiece is still on the suction cup: stop taking orders and wait for a human (never go on to pick the next one)
if (robotFaulted[robotId])
{
Thread.Sleep(100);
continue;
}
// Claim: find in the queue the target nearest to you and within the working radius
var target = TryClaimNearest(robotId);
if (target != null)
{
robotBusy[robotId] = true;
try
{
ExecutePickAndPlace(robotId, target);
}
finally
{
robotBusy[robotId] = false;
}
}
else
{
Thread.Sleep(1);
}
}
}
/// <summary>
/// Claim the nearest unassigned target from the shared queue
/// Target travel distance = current encoder - encoder at detection, compared against the robot position
/// </summary>
SortingTarget TryClaimNearest(int robotId)
{
int encoder = GetEncoder();
int robotPos = GetRobotPosition(robotId);
lock (listLock)
{
SortingTarget best = null;
int bestDist = int.MaxValue;
foreach (var t in targetList)
{
if (t.AssignedRobot != -1) continue;
// Distance the target has travelled since leaving the camera
int travelDistance = encoder - t.EncoderAtDetect;
// Only claim targets that have not passed you yet: gap = robot absolute position - target's current position.
// gap < 0 = the target is already past and cannot be caught up; using |travelDistance - robotPos| would turn
// Targets that have already passed are claimed too; they will then be aborted out of range in TrackDescend.
int gap = robotPos - travelDistance;
if (gap >= 0 && gap < WorkRadius && gap < bestDist)
{
best = t;
bestDist = gap;
}
}
if (best != null)
best.AssignedRobot = robotId;
return best;
}
}
/// <summary>
/// Clear over-distance targets - a target that has travelled further than the total conveyor length is treated as dropped
/// </summary>
void PurgeExpiredTargets()
{
int encoder = GetEncoder();
lock (listLock)
{
int removed = targetList.RemoveAll(t =>
{
if (t.AssignedRobot >= 0) return false;
int travelDistance = encoder - t.EncoderAtDetect;
return travelDistance > ConveyorLength;
});
if (removed > 0)
Console.WriteLine($"剔除 {removed} 个超距目标 (掉落)"); // Rejected {removed} out-of-range targets (dropped)
}
}
// ============ Pick/place (an auxiliary service provides the inverse kinematics) ============
/// <summary>
/// Perform pick -> place -> return
/// Enable line tracking during the pick phase: the unified PDO callback recomputes the target position every cycle to compensate for belt motion
/// Inverse kinematics supplies the pulse values externally
/// </summary>
void ExecutePickAndPlace(int robotId, SortingTarget target)
{
int robotPos = GetRobotPosition(robotId);
// 1. Line-tracking descent: the target pose travels with the belt while descending to the pick height
bool ok = TrackAndDescend(robotId, target, robotPos);
bool holding = false; // Whether the workpiece is already on the suction cup
// 2. Open the suction cup and keep tracking the belt while the vacuum builds.
// Just sleeping does not move: within 50 ms the workpiece is carried another 75 mm (1.5 m/s), so the suction cup will certainly lose it.
if (ok)
{
SetSuction(robotId, true);
holding = true;
ok = TrackHold(robotId, target, robotPos, SUCTION_SETTLE_SECONDS);
}
// 3. Lift -> move to the bin -> release -> return to the standby position (each segment is three-axis synchronised)
var ik = IKService.Compute(0, target.PixelY);
if (ok) ok = MoveAxes(robotId, ik.LiftPulses);
if (ok) ok = MoveAxes(robotId, ik.PlacePulses);
// Release only when actually above the bin; a mid-way failure must hold the vacuum and stop for a human, never dropping the part in mid-air
if (ok)
{
SetSuction(robotId, false);
holding = false;
Thread.Sleep(30);
ok = MoveAxes(robotId, ik.StandbyPulses);
}
else if (holding)
{
robotFaulted[robotId] = true;
Console.WriteLine($"[报警] 机器人{robotId}: 目标{target.Id} 搬运失败, 保持真空 (工件仍在吸盘上), 本机停止接单, 需人工处理"); // [Alarm] Robot{robotId}: transfer of target{target.Id} failed, vacuum kept (the workpiece is still on the suction cup), this machine stops accepting jobs, manual handling required
}
// Remove it from the queue whether the pick completes or is aborted (the target is stale either way)
lock (listLock) { targetList.Remove(target); }
Console.WriteLine(ok
? $"机器人{robotId}: 完成目标{target.Id}, 类别{target.Category}" // Robot{robotId}: target{target.Id} completed, category{target.Category}
: $"机器人{robotId}: 目标{target.Id} 运动中中止"); // Robot{robotId}: target{target.Id} aborted mid-motion
}
/// <summary>
/// Keep line tracking while waiting for the vacuum to build or release: the target keeps being recomputed from the current encoder and the robot follows the workpiece.
/// TrackHold does no position interpolation (it sends the pick pose directly each tick); it simply replaces "hold still" with "follow synchronously".
/// </summary>
bool TrackHold(int robotId, SortingTarget target, int robotPos, double seconds)
{
var mo = motions[robotId];
lock (mo)
{
mo.TrackTargetEncoder = target.EncoderAtDetect;
mo.TrackPixelY = target.PixelY;
mo.TrackRobotPos = robotPos;
mo.DurationSeconds = seconds;
mo.Aborted = false;
mo.Completed.Reset();
mo.StartTs = Stopwatch.GetTimestamp();
mo.Kind = MoveKind.TrackHold;
}
if (!mo.Completed.Wait(TimeSpan.FromSeconds(seconds + 2.0)))
{
lock (mo) { mo.Kind = MoveKind.Idle; }
return false;
}
return !mo.Aborted && !pdoFaulted;
}
/// <summary>
/// Line-tracking descent: after the command is loaded, the PDO callback recomputes the "pick pose that travels with the belt" every cycle,
/// ...and use the same time-base progress for the descent interpolation, so the pick point keeps tracking the target.
/// </summary>
bool TrackAndDescend(int robotId, SortingTarget target, int robotPos)
{
var mo = motions[robotId];
lock (mo)
{
for (int j = 0; j < AXES_PER_ROBOT; j++)
mo.StartPulses[j] = master.Slaves[GetMotorSlaveIndex(robotId, j)]
.PDO.InputsMapping<StepperMotor_Input>().ActualPosition;
mo.TrackTargetEncoder = target.EncoderAtDetect;
mo.TrackPixelY = target.PixelY;
mo.TrackRobotPos = robotPos;
mo.DurationSeconds = TRACK_DESCEND_SECONDS;
mo.Aborted = false;
mo.Completed.Reset();
mo.StartTs = Stopwatch.GetTimestamp();
mo.Kind = MoveKind.TrackDescend;
}
if (!mo.Completed.Wait(TimeSpan.FromSeconds(TRACK_DESCEND_SECONDS + 2.0)))
{
lock (mo) { mo.Kind = MoveKind.Idle; }
return false;
}
return !mo.Aborted && !pdoFaulted;
}
// ============ Low-level EtherCAT operations ============
/// <summary>
/// Three-axis synchronised motion: loads the time-base interpolation parameters; the targets are written to the PDO by the callback using the same progress.
/// Duration = max(|travel| / joint max speed) / (1 - acceleration share); the slowest joint sets the pace and all three axes arrive together.
/// </summary>
bool MoveAxes(int robotId, int[] pulses)
{
var mo = motions[robotId];
double duration = 0;
lock (mo)
{
for (int j = 0; j < AXES_PER_ROBOT; j++)
{
mo.StartPulses[j] = master.Slaves[GetMotorSlaveIndex(robotId, j)]
.PDO.InputsMapping<StepperMotor_Input>().ActualPosition;
mo.EndPulses[j] = pulses[j];
double t = Math.Abs(pulses[j] - mo.StartPulses[j]) / (double)JointMaxSpeedPps[j];
if (t > duration) duration = t;
}
// Trapezoid peak = joint max velocity, total duration = travel/max velocity / (1 - acceleration share)
duration = Math.Max(duration, 0.02) / (1.0 - ACCEL_TIME_FRACTION);
mo.DurationSeconds = duration;
mo.Aborted = false;
mo.Completed.Reset();
mo.StartTs = Stopwatch.GetTimestamp();
mo.Kind = MoveKind.Move;
}
if (!mo.Completed.Wait(TimeSpan.FromSeconds(duration + 2.0)))
{
lock (mo) { mo.Kind = MoveKind.Idle; }
return false;
}
return !mo.Aborted && !pdoFaulted;
}
// ============ Unified real-time motion loop ============
/// <summary>
/// PDO cycle callback (once per CYCLE_NS): walks 6 robots x 3 axes (18 axes in total),
/// Compute targets from the same time base and write the control word and target position in the same frame.
/// The robot thread only writes MoveKind / interpolation parameters and never writes the PDO directly;
/// For disabled / faulted / QuickStop axes the target always equals the actual position.
/// </summary>
void OnPdoCycle(ushort mi)
{
var m = master;
if (m == null) return;
try
{
int encoder = GetEncoder();
long now = Stopwatch.GetTimestamp();
for (int r = 0; r < ROBOT_COUNT; r++)
{
var mo = motions[r];
MoveKind kind;
long startTs;
double seconds;
int trackEncoder, trackPixelY, trackPos;
lock (mo)
{
kind = mo.Kind;
startTs = mo.StartTs;
seconds = mo.DurationSeconds;
trackEncoder = mo.TrackTargetEncoder;
trackPixelY = mo.TrackPixelY;
trackPos = mo.TrackRobotPos;
}
// Time-base progress: depends only on elapsed time, not on how many times the callback actually ran
double elapsed = (now - startTs) / (double)Stopwatch.Frequency;
double progress = kind == MoveKind.Idle ? 1.0
: seconds > 0 ? Math.Min(1.0, elapsed / seconds) : 1.0;
double s = TrapezoidRatio(progress);
// Line tracking: the pick pose itself travels with the belt, recomputed every cycle from the current encoder.
// TrackDescend descends while tracking; TrackHold only follows (while waiting for the vacuum to build or release)
int[] grab = null;
if (kind == MoveKind.TrackDescend || kind == MoveKind.TrackHold)
{
int relX = (encoder - trackEncoder) - trackPos;
if (Math.Abs(relX) > WorkRadius)
{
// The target is beyond the working radius: abort this robot; this tick still writes the Idle safety frame (target = actual)
lock (mo) { mo.Kind = MoveKind.Idle; }
mo.Aborted = true;
mo.Completed.Set();
kind = MoveKind.Idle;
}
else
{
grab = IKService.ComputeGrab(relX, trackPixelY).GrabPulses;
}
}
bool allEnabled = true;
bool arrived = true;
bool resetActive = false;
bool followingErrorTooLarge = false;
for (int j = 0; j < AXES_PER_ROBOT; j++)
{
int idx = GetMotorSlaveIndex(r, j);
ref var o = ref m.Slaves[idx].PDO.OutputsMapping<StepperMotor_Output>();
ref readonly var i = ref m.Slaves[idx].PDO.InputsMapping<StepperMotor_Input>();
ushort sw = i.StatusWord;
bool enabled = (sw & 0x6F) == 0x27;
allEnabled &= enabled;
// 0x60F4 following error limit exceeded = crash / lost steps: abort this tick immediately, do not keep moving with the error
followingErrorTooLarge |= Math.Abs(i.FollowError) > MaxFollowingErrorPulses;
// Fault reset: low phase 0x0006 -> high phase 0x0086, creating a bit7 rising edge over two cycles.
// Never use 0x0000 (bit2=0 would hold QuickStop) / 0x0080 (same).
// Send the pulse only to axes genuinely in Fault ((sw & 0x4F)==0x08); a healthy axis gets switched off first (T8).
int ai = r * AXES_PER_ROBOT + j;
if (faultResetRequested[ai] && (sw & 0x4F) != 0x08)
faultResetRequested[ai] = false;
bool axisReset = faultResetRequested[ai];
ushort cw;
if (axisReset)
{
resetActive = true;
if (faultResetPhase[ai] == 0) { cw = 0x0006; faultResetPhase[ai] = 1; }
else { cw = 0x0086; faultResetPhase[ai] = 0; faultResetRequested[ai] = false; }
}
else
{
cw = StepCiA402(sw, servoEnable);
}
// Target = actual (default) guarantees no jump while disabled / faulted / QuickStop / in reset
int desired = i.ActualPosition;
if (enabled && kind != MoveKind.Idle && !axisReset)
{
int end = kind == MoveKind.Move ? mo.EndPulses[j] : grab[j];
// TrackHold sends the following pose directly and does no position interpolation (otherwise it would sweep past the descent start point)
desired = kind == MoveKind.TrackHold
? end
: mo.StartPulses[j] + (int)Math.Round((end - mo.StartPulses[j]) * s);
}
o.ControlWord = cw;
o.TargetPosition = desired;
// The suction cup DO is written in the same frame as 0x6040 / 0x607A; only Joint 0's DO1 drives the solenoid valve
if (j == 0)
o.DigitalOutputs = Volatile.Read(ref suctionRequested[r]) != 0 ? DO_SUCTION : 0u;
arrived &= Math.Abs(i.ActualPosition - desired) <= ARRIVE_TOLERANCE;
}
if (kind == MoveKind.Idle) continue;
if (!allEnabled || resetActive || followingErrorTooLarge)
{
// Lost enable / fault reset / following error limit exceeded: abort at once, the target is already back to actual
lock (mo) { mo.Kind = MoveKind.Idle; }
mo.Aborted = true;
mo.Completed.Set();
continue;
}
// Time base exhausted + (really in position or the settling window used up) -> this move is complete
if (progress >= 1.0 && (arrived || elapsed >= seconds + SETTLE_SECONDS))
{
lock (mo) { mo.Kind = MoveKind.Idle; }
mo.Completed.Set();
}
}
}
catch (Exception ex)
{
// A callback exception is never thrown back to the master thread: latch the fault and wake all waiters (pdoFaulted is not cleared automatically,
// Any callback exception requires stopping and checking; it must not keep running as if healthy)
pdoFaulted = true;
Console.WriteLine($"[报警] PDO 周期回调异常: {ex.GetType().Name}: {ex.Message}"); // [Alarm] PDO cyclic callback exception: {ex.GetType().Name}: {ex.Message}
for (int r = 0; r < ROBOT_COUNT; r++) motions[r].Completed.Set();
}
}
/// <summary> 0x6060: write CSP(8) and read it back to verify (this PDO mapping contains no mode word) </summary>
static bool SetCspMode(DarraEtherCAT.Slave slave, ushort modeIndex)
{
// slave.CoE is CoEInstance? - null when this slave does not support CoE, must be checked before sending
var coe = slave.CoE;
if (coe == null) return false;
if (!coe.SDOWrite(modeIndex, 0, new byte[] { unchecked((byte)MODE_CSP) })) return false;
coe.SDORead(modeIndex, 0, out SdoReadResult r, false);
return r.Ok && r.Data != null && r.Data.Length == 1 && r.Data[0] == MODE_CSP;
}
/// <summary>
/// CiA 402 control word state machine (driven by the status word every cycle)
/// State check: (sw & 0x6F) running state / (sw & 0x4F)==0x08 fault
/// Always send 0x0006 (Shutdown) when enable has not been requested; never auto-enable
/// The fault reset pulse is generated by the caller over two phases, 0x0006 -> 0x0086; this function is not responsible for it
/// </summary>
static ushort StepCiA402(ushort sw, bool enable)
{
// QuickStopActive must be left first (T12 = Disable Voltage): 0x0006 in QuickStopActive
// It is an illegal transition and will be stuck in 0x07 forever. This step is independent of the enable request and must be done even when disabled.
// Note: QuickStop is a stop event; if the field treats it as an emergency stop, the upper layer should withdraw servoEnable when it sees 0x07,
// After exiting it rests in SwitchOnDisabled / ReadyToSwitchOn and must be re-enabled by a human.
if ((sw & 0x6F) == 0x07) return 0x0000;
if (!enable) return 0x0006; // Disabled: hold Shutdown
if ((sw & 0x4F) == 0x08) return 0x0006; // Fault: hold Shutdown and wait for a manual reset
switch (sw & 0x6F)
{
case 0x40: return 0x0006; // SwitchOnDisabled → Shutdown
case 0x21: return 0x0007; // ReadyToSwitchOn → Switch On
case 0x23: return 0x000F; // SwitchedOn → Enable Operation
case 0x27: return 0x000F; // OperationEnabled
case 0x00: return 0x0006; // NotReadyToSwitchOn -> wait for the automatic T1
case 0x0F: return 0x0006; // FaultReactionActive -> wait for the automatic transition to Fault
default: return 0x0000; // Illegal status word: fail-safe, cut torque
}
}
/// <summary>
/// Time-base trapezoidal velocity profile (20% acceleration / 60% constant / 20% deceleration), input and output normalised to 0..1
/// </summary>
static double TrapezoidRatio(double p)
{
const double V = 1.0 / (1.0 - ACCEL_TIME_FRACTION); // Normalised velocity of the constant-speed segment, so that s(1)=1
if (p <= 0) return 0;
if (p >= 1) return 1;
if (p < ACCEL_TIME_FRACTION) return 0.5 * V * p * p / ACCEL_TIME_FRACTION;
if (p > 1 - ACCEL_TIME_FRACTION)
{
double q = 1 - p;
return 1 - 0.5 * V * q * q / ACCEL_TIME_FRACTION;
}
return 0.5 * V * ACCEL_TIME_FRACTION + V * (p - ACCEL_TIME_FRACTION);
}
/// <summary>
/// Control the suction cup - Joint 0 motor DO1.
/// Only the request is registered here; 0x60FE:01 in the process image is written by the PDO callback in the same PDO frame,
/// Prevents the robot thread and the RT thread from doing read-modify-write on the same output area and losing updates.
/// </summary>
void SetSuction(int robotId, bool on)
=> Volatile.Write(ref suctionRequested[robotId], on ? 1 : 0);
/// <summary>
/// Read the laser sensor - Joint 0 motor DI4
/// </summary>
public bool IsObjectDetected(int robotId)
{
ref readonly var inp = ref master.Slaves[GetMotorSlaveIndex(robotId, 0)].PDO.InputsMapping<StepperMotor_Input>();
return (inp.DigitalInputs & DI_LASER) != 0;
}
static void Main(string[] args) => new DeltaSortingController().Run();
}
Example of the vision system enqueueing targets:
// Vision AI thread: calls EnqueueTarget to queue after the line-scan camera recognises a part
// The controller's robot threads automatically claim the nearest target from the queue and execute it
var ctrl = new DeltaSortingController();
// The camera AI recognised a target
ctrl.EnqueueTarget(new SortingTarget
{
Id = 42,
EncoderAtDetect = 156000, // Encoder pulse value at detection
PixelY = 1280, // Vertical conveyor direction offset (pixels, camera coordinates)
Category = 2, // AI classification: PP plastic
});
- Do not mix the two pulse domains: the conveyor side uses EL5001 encoder pulses (15000 pulses/m), while the joint side uses the drive position unit of
0x6064/0x607A. The first argument ofIKServiceis the conveyor encoder offset of the target relative to the robot's absolute position, and the second is the camera pixel Y; the service must convert both to joint pulses itself, so the caller must not convert half of it in advance. Re-check the physical meaning of these two arguments whenever the camera, the lens or the timing pulley changes. - Cycle: bus cycle =
LoopCycle(ns) = DC Sync0 = the interpolation time base of the 18 axes; all three hold the same value. The0x60C2interpolation time period (value × 10^exponent seconds) must equal it — for 500 µs write0x60C2:01 = 50,:02 = -5. - Synchronization: compute all 18 axis targets in the same callback, then write them into the process image together as one PDO frame; do not submit per robot, otherwise the robots in the same frame sit at different points in time.
- Line tracking: the pick is not just "descend to the pick pose"; while the vacuum builds (
SUCTION_SETTLE_SECONDS) the robot must keep following the conveyor (TrackHold), otherwise at a belt speed of 1.5 m/s it drifts 75 mm in 50 ms and the suction cup comes off. - Following error: in CSP the drive closes the loop and the master only supplies a position each cycle; to reduce the following error, use velocity feedforward
0x60B1/ torque feedforward0x60B2(they take effect only when mapped into the RxPDO). This example uses two criteria: a stop on0x60F4over-limit and an in-position window on0x6064. - Joint soft limits: this page leaves reachability to the inverse kinematics, but in production you must still check the soft limits per axis in joint pulses on the PDO output side and stop the axis with an alarm when a limit is exceeded — a wrong IK result, calibration drift or mechanical deformation will not be stopped by an operator button.
- Direction and zero position: the EL5001 counting direction must match the direction in which targets travel from the camera to the robots (if it does not,
encoder - EncoderAtDetectbecomes negative and every target is judged out of range); take the joint zero position and the0x607Eposition polarity from calibration on the real machine.
Complete example code
This page is a scenario description. For runnable references, see Panasonic_ConveyorSync (a complete project with conveyor following, material tracking and CSP master/slave synchronization with flying pick) and STF-EC_SyncAxis (multi-axis CSP with per-axis output from the same ProcessDataCyclicSync and per-axis fault reset). The delta robot inverse kinematics, line-scan camera AI recognition and the shared multi-robot target queue are specific to this page's scenario; the reference projects contain no corresponding implementation.