Skip to main content

36-servo singulation system

Control type: speed control for 36 independent roller zones

This page covers speed control for 36 independent roller zones (CiA 402 CSV, 0x6060 = 9), not synchronized axes / electronic gearing. Each zone's speed is set individually by the vision matrix according to the parcel position; there is no master/slave coupling between zones and no gear ratio relationship. For multi-axis motion linked at a fixed ratio, see Synchronized axes / electronic gearing.

Hardware configuration​

  • Master: Windows 10 × 1 + Intel i5 × 1
  • Motion control: JMC JAWD-C2 EtherCAT dual-axis servo drives × 18 + ≥200 W high-torque servo motors × 36
  • Vision system: Hikvision MV-CS060-10GC area-scan industrial camera × 1 (looking down at the roller bed, identifying parcel position and outline)
Dual-axis drive approach

The JMC JAWD-C2 dual-axis servo drive controls two roller motors on one drive (Axis A + Axis B), so 18 drives cover the 36 roller segments. Compared with 36 single-axis drives, this halves the device count, shortens the EtherCAT bus frame length, and reduces wiring complexity.

Counting conventions: bus slaves = 18 (one dual-axis drive counts as one slave), axes = 36 (each slave has 2 axes, each with its own set of CiA 402 objects: the Axis B object index = Axis A + 0x0800, for example 0x6041 → 0x6841, 0x6060 → 0x6860). In the code on this page, DRIVE_COUNT = 18 means the slave count and ZONE_COUNT = 36 means the axis count (= the roller zone count); the two must not be mixed up.

Cost analysis​

CategoryModel / specificationReference unit price (¥)QtySubtotal (¥)
Dual-axis servo driveJMC JAWD-C21,6001828,800
Servo motor≥200 W high-torque servo (selected by load)4503616,200
Area-scan industrial cameraHikvision MV-CS060-10GC3,00013,000
Industrial PCIntel i5 class3,50013,500
Reference total for the line≈ ¥51,500

The prices above are reference prices for the core components (RMB) and exclude the roller frame, cables and similar items. Motor power must be selected against the actual roller load, parcel weight and acceleration/deceleration requirements; heavy-load installations may need 400 W or more, and stepper motors are also an option.

Performance figures​

  • Throughput: ≥ 6000 parcels/hour
  • Singulation success rate: ≥ 99.5%
  • Roller bed: 6 rows × 6 columns, handles parcels from 50 mm to 800 mm
  • Maximum conveying speed: 2.5 m/s
  • PDO cycle: 500 µs (or 1 ms, see below)

Control cycle and DC synchronization​

  • The cycle is determined by master.LoopCycle alone; the example uses 500 µs, and 1 ms also works. Roller conveying is a velocity-loop application, and both 500 µs and 1 ms meet 6000 parcels/hour: choose 1 ms when industrial PC CPU load matters, 500 µs when you want finer speed steps.
  • DC Sync0 must have the same value as LoopCycle (slave.ConfigureDC(cycleNs)). Setting the cycle without configuring DC makes the frame cadence and the slave SYNC0 lose synchronization, and the velocity loop shows periodic jitter.
  • Do not write 125 µs without configuring it: 125 µs is the recommended starting point on Windows (a recommendation, not a product limit; there is no product lower bound on the cycle). You must set LoopCycle = 125000 and ConfigureDC(125000) together and measure the actual frame length and jitter; this case does not need a cycle that short.
  • Once the cycle is fixed, every quantity derived from it (fault reset hold cycles, speed update cadence, status polling interval) is derived from master.LoopCycle; do not hard-code 1 ms.

Speed units​

  • 0x60FF (target velocity) and 0x606C (actual velocity) use the drive velocity unit = position units per second, determined by the 0x6091 gear ratio and the 0x6092 feed constant; in common servo configurations it is rpm, but it is not a fixed unit defined by the protocol. SpeedMatrix on this page is filled in rpm.
  • If the process specifies a linear speed (mm/s), convert it to drive units in the application layer before writing the matrix: v_rpm = v_mm_s × 60 / (π × 辊筒直径 mm). All 36 zones must use the same unit — with half filled in rpm and half in mm/s, the speed difference between adjacent zones is computed completely wrong and the parcels never separate.

Slave-loss / enable-loss monitoring​

  • Slave loss and link diagnostics belong on the non-real-time reporting thread (one tick every 100 ms in the example), not polled inside the RT callback: slave.IsLost, slave.State != EcState.OP, master.LinkState, and WKC.
  • WKC is exposed at master level as master.Diagnostics.WKC / master.Diagnostics.ExpectedWKC (both ushort); for a per-group view use master.Groups[g].ActualWKC / .ConsecutiveMiss / .TotalFrames / .MismatchFrames. ExpectedWKC is a fixed truth established at configuration time, and only WKC < ExpectedWKC means a mapped slave is not contributing (slave loss / hot-plug); the actual value recovers by itself once the slave is back. ExpectedWKC == 0 only means the expected value has not been established yet and must not be read as "no shortfall".
  • Hot-plug is a product capability: when one drive drops off the bus or is power-cycled while running, the master keeps sending frames on schedule and the other 17 drives are unaffected; the dropped slave reports slave.IsLost == true and the WKC deficit grows, and after recovery that slave walks INIT→PREOP→SAFEOP→OP on its own, IsLost returns false and the WKC recovers. The application layer's job is to zero that axis's speed and raise an alarm, not to stop the whole bus.
  • The RT callback guarantees exactly one thing: an axis that is not OperationEnabled always has a speed of 0 (StepAxis already forces 0 from the status word). Alarms and whether the whole line stops are decisions for the monitoring thread; do not wait for the axis to recover by keeping on sending the matrix.

Application scenario​

A singulation machine (singulator) in an express parcel sorting center. The 36 independent roller segments form a roller bed arranged as a 6-row × 6-column matrix. Parcels enter in bulk from the inlet side and lie stacked or touching on the bed. An area-scan camera looks straight down at the whole matrix and identifies each parcel's position and outline in real time. The vision algorithm assigns a different speed to each roller zone, and the speed difference between adjacent zones gradually opens a gap between touching parcels; they finally leave the outlet side in a single row and go to the downstream cross-belt sorter for individual handling.

System architecture​

Machine vision approach

This case shows only a basic single-camera setup. Possible extensions include multi-camera stitching to cover a very wide roller bed, 3D structured light for parcel volume measurement, and deep-learning parcel segmentation and tracking; these are not included in the EtherCAT master software license.

Code example​

PDO struct definitions​

using System.Runtime.InteropServices;

/// <summary>
/// JMC JAWD-C2 dual-axis servo drive input PDO (TxPDO)
/// CSV mode: 0x1A00 (Axis A) + 0x1A10 (Axis B)
/// CiA 402 multi-axis: Axis B object index = Axis A + 0x0800
/// Byte count: 2+4+4+2+4 = 16 B per axis, 32 B for the dual axis (must equal slave.Ibytes)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct JAWD_Input
{
// ---- Axis A ----
public ushort StatusWord_A; // 0x6041:00 status word
public int ActualPosition_A; // 0x6064:00 actual position (drive position units)
public int ActualVelocity_A; // 0x606C:00 actual velocity (drive velocity units, typically rpm)
public short ActualTorque_A; // 0x6077:00 actual torque (‰ of rated)
public uint DigitalInputs_A; // 0x60FD:00 drive digital inputs

// ---- Axis B ----
public ushort StatusWord_B; // 0x6841:00 status word
public int ActualPosition_B; // 0x6864:00 actual position (drive position units)
public int ActualVelocity_B; // 0x686C:00 actual velocity (drive velocity units, typically rpm)
public short ActualTorque_B; // 0x6877:00 actual torque (‰ of rated)
public uint DigitalInputs_B; // 0x68FD:00 drive digital inputs
}

/// <summary>
/// JMC JAWD-C2 dual-axis servo drive output PDO (RxPDO)
/// CSV mode: 0x1600 (Axis A) + 0x1610 (Axis B)
/// Byte count: 2+1+4 = 7 B per axis, 14 B for the dual axis (must equal slave.Obytes)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct JAWD_Output
{
// ---- Axis A ----
public ushort ControlWord_A; // 0x6040:00 control word
public sbyte ModesOfOperation_A; // 0x6060:00 mode of operation (9=CSV)
public int TargetVelocity_A; // 0x60FF:00 target velocity (drive velocity units, typically rpm)

// ---- Axis B ----
public ushort ControlWord_B; // 0x6840:00 control word
public sbyte ModesOfOperation_B; // 0x6860:00 mode of operation (9=CSV)
public int TargetVelocity_B; // 0x68FF:00 target velocity (drive velocity units, typically rpm)
}

/// <summary>
/// Roller zone (one cell of the 6x6 matrix, internal use)
/// </summary>
public class RollerZone
{
public int DriveIndex; // Corresponding JAWD drive slave index
public bool IsAxisB; // true=AxisB, false=AxisA
}

Control code​

using System;
using System.Runtime.InteropServices;
using System.Threading;
using DarraEtherCAT_Master;

/// <summary>
/// Single-item separation controller
/// Responsibility: EtherCAT servo management, exposing a 6x6 speed control matrix
/// The separation algorithm is implemented independently by the vision system and sends each zone's target speed (rpm) through SpeedMatrix
/// </summary>
class SingulationController
{
const int ROWS = 6;
const int COLS = 6;
const int ZONE_COUNT = ROWS * COLS; // 36
const int DRIVE_COUNT = 18;
const int SLAVE_DRIVE_START = 0;
const sbyte MODE_CSV = 9;

// Internal drive mapping (row-major, each JAWD drive covers the two adjacent zones on its row)
readonly RollerZone[,] grid = new RollerZone[ROWS, COLS];

// State shared with the cycle callback
DarraEtherCAT master;
volatile bool isRunning;
volatile bool servoEnableRequested; // true=callback advances the enable from the status word; false=always send the stop command 0x0006
volatile int enabledAxisSnapshot; // The callback only writes snapshots; printing/reporting happens on a non-real-time thread
volatile int cycleErrorCount; // Callback exception counter (only counted; the text is produced in the main loop)
volatile string cycleErrorText;
int[,] driveZone; // [d, 0]=rowA, [d,1]=colA, [d,2]=rowB, [d,3]=colB

// CiA 402 fault reset edge (per axis): >0 means the following ticks are still in that phase
readonly int[] resetLowCycles = new int[ZONE_COUNT];
readonly int[] resetHighCycles = new int[ZONE_COUNT];
volatile int resetGateCycles; // >0: inside the reset pulse window, so do not judge Fault as an enable failure

// Enable wait: set by the PDO callback from the real status word; the main thread only waits on the event instead of guessing the timing
readonly ManualResetEventSlim handshakeDone = new ManualResetEventSlim(false);
volatile bool handshakeFailed;

// ============ External control matrix (read and written by the vision system) ============

/// <summary>
/// 6x6 roller speed control matrix, unit: drive speed units (typically rpm, see "speed unit" above)
/// The vision system writes each zone's target speed directly and the controller syncs it to the servos every EtherCAT cycle
/// SpeedMatrix[row, col]: row 0=infeed side, row 5=outfeed side
/// </summary>
public readonly int[,] SpeedMatrix = new int[ROWS, COLS];

// ============ Main flow ============

/// <summary>
/// Build the zone -> drive (Axis A/B) mapping and derive from it the "drive -> row/column" index table used by the callback.
/// The mapping is defined in this one place only; driveZone is its precomputed real-time projection - do not compute it again elsewhere.
/// 6 columns is even, so the two linear-zone numbers of every dual-axis drive must fall on the same row (two adjacent zones on that row).
/// </summary>
void InitGrid()
{
for (int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
int linearIdx = r * COLS + c;
grid[r, c] = new RollerZone
{
DriveIndex = SLAVE_DRIVE_START + (linearIdx / 2),
IsAxisB = (linearIdx % 2) == 1
};
}
}

// The callback needs it, so build it before attaching the callback: [d, 0]=rowA, [d,1]=colA, [d,2]=rowB, [d,3]=colB
driveZone = new int[DRIVE_COUNT, 4];
for (int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
int d = grid[r, c].DriveIndex - SLAVE_DRIVE_START;
int axisBase = grid[r, c].IsAxisB ? 2 : 0;
driveZone[d, axisBase] = r;
driveZone[d, axisBase + 1] = c;
}
}
}

void Run()
{
InitGrid();

// DENI = the network configuration the master configuration tool exports after scanning the real slaves (topology + PDO assignment); do not edit it by hand
DarraEtherCAT.BuildResult build = new DarraEtherCAT()
.SetNetwork("EtherCAT 网卡名") // Specify explicitly when there are several NICs; otherwise Build automatically picks the first wired NIC with the link Up
.SetENI("config.deni")
.Build();

if (!build.Success)
{
Console.WriteLine($"主站初始化失败: {build.Message}"); // Master initialization failed: {build.Message}
return;
}
master = build.Master!;

try
{
Console.WriteLine($"发现 {master.SlaveCount} 个从站"); // Found {master.SlaveCount} slaves
if (master.SlaveCount < SLAVE_DRIVE_START + DRIVE_COUNT)
{
Console.WriteLine($"从站数量不足: 需要 {DRIVE_COUNT} 台 JAWD 双轴驱动器, 实际扫描到 {master.SlaveCount} 台"); // Not enough slaves: {DRIVE_COUNT} JAWD dual-axis drives needed, only {master.SlaveCount} found by the scan
return;
}

// Cycle time: transport is a velocity-loop application, 500 µs / 1 ms both work; choose one based on throughput and IPC load.
// Once set, derive every cycle-related quantity from it; do not write 500 µs in one place and convert from 1 ms in another.
uint cycleNs = 500_000;
master.LoopCycle = cycleNs;
if (master.LoopCycle != cycleNs)
{
Console.WriteLine($"LoopCycle 设定失败: 请求 {cycleNs}ns, 读回 {master.LoopCycle}ns"); // LoopCycle setup failed: {cycleNs}ns requested, {master.LoopCycle}ns read back
return;
}
Console.WriteLine($"PDO 周期: {cycleNs / 1000}µs"); // PDO cycle time: {cycleNs / 1000}µs

// DC configuration must come after PreOp: SM2 is not active yet, which is what makes it possible to write 0x1C32:01 / 0x09A0;
// SYNC0 itself is armed by the SDK before entering SafeOp/OP. Configuring DC in Init has no writable Sync Manager context.
if (!master.SetState(EcState.PreOp, out string preOpError))
{
Console.WriteLine($"无法进入 PreOp 状态: {preOpError}"); // Failed to enter the PreOp state: {preOpError}
return;
}

// The PDO struct must match the drive's TxPDO / RxPDO byte count exactly: Pack=1 removes alignment padding,
// Field order = PDO mapping order. Ibytes / Obytes live on Slave, not on PDO;
// The process image byte count is only fixed after entering PreOp, so this check happens after the state advance.
int inBytes = Marshal.SizeOf<JAWD_Input>();
int outBytes = Marshal.SizeOf<JAWD_Output>();
var probe = master.Slaves[SLAVE_DRIVE_START];
if ((uint)inBytes != probe.Ibytes || (uint)outBytes != probe.Obytes)
{
Console.WriteLine($"PDO 结构体尺寸不匹配: 结构体 {inBytes}/{outBytes} B, " + // PDO struct size mismatch: struct {inBytes}/{outBytes} B,
$"驱动器 {probe.Ibytes}/{probe.Obytes} B — 检查 DENI 的 PDO 映射与结构体字段顺序"); // drive {probe.Ibytes}/{probe.Obytes} B — check the DENI PDO mapping against the struct field order
return;
}

// DC Sync0 equals LoopCycle; drives without DC still run (the velocity loop does not depend on SYNC0 phase lock)
for (int d = 0; d < DRIVE_COUNT; d++)
{
var slave = master.Slaves[SLAVE_DRIVE_START + d];
if (slave.HasDC && !slave.ConfigureDC(cycleNs))
Console.WriteLine($"驱动器 {d} DC Sync0 配置失败, 按 FreeRun 继续"); // Drive {d} DC Sync0 configuration failed, continuing in FreeRun
}

// Reach SafeOp first: the process image is usable after SafeOp, so write the "safety frame" in and then enter OP.
// Going straight to OP means the first frame after entering OP is the process image default (all fields 0): 0x6040 = 0x0000 is Disable Voltage,
// 0x6060 = 0 means "no mode" - such a frame must not be sent as the first power-on frame to the 36 drives.
if (!master.SetState(EcState.SafeOp, out string safeOpError))
{
Console.WriteLine($"无法进入 SafeOp 状态: {safeOpError}"); // Failed to enter the SafeOp state: {safeOpError}
return;
}
for (int d = 0; d < DRIVE_COUNT; d++)
{
ref var outInit = ref master.Slaves[SLAVE_DRIVE_START + d].PDO.OutputsMapping<JAWD_Output>();
outInit.ControlWord_A = 0x0006; outInit.ControlWord_B = 0x0006; // Shutdown = the real stop command
outInit.ModesOfOperation_A = MODE_CSV; outInit.ModesOfOperation_B = MODE_CSV;
outInit.TargetVelocity_A = 0; outInit.TargetVelocity_B = 0;
}

if (!master.SetState(EcState.OP, out string opError))
{
Console.WriteLine($"无法进入 OP 状态: {opError}"); // Failed to enter the OP state: {opError}
return;
}

// Attach the cycle callback first: the enable handshake is also advanced by it per cycle from the status word, instead of guessing the timing with a fixed Sleep
isRunning = true;
master.Events.ProcessDataCyclicSync += OnPdoCycle;

if (!EnableAllServos())
{
Console.WriteLine("使能未完成 (超时或有轴处于故障), 请检查驱动器"); // Enable did not complete (timeout, or an axis is in fault), check the drives
return;
}

Console.WriteLine("36伺服单件分离系统启动!"); // 36-servo single-piece separation system started!
Console.WriteLine($"辊筒矩阵: {ROWS}×{COLS}, 等待视觉系统写入 SpeedMatrix...\n"); // Roller matrix: {ROWS}×{COLS}, waiting for the vision system to write SpeedMatrix...

// Keep running and wait for the vision system to keep writing SpeedMatrix; status reporting lives here, not in the PDO callback
var lastLog = DateTime.UtcNow;
int lastCycleErrorCount = 0;
while (isRunning)
{
Thread.Sleep(100);
if (cycleErrorCount != lastCycleErrorCount) // Callback exceptions land here (no IO inside the RT callback)
{
lastCycleErrorCount = cycleErrorCount;
Console.WriteLine($"周期回调异常 ×{lastCycleErrorCount}: {cycleErrorText}"); // Cyclic callback exception ×{lastCycleErrorCount}: {cycleErrorText}
}
if ((DateTime.UtcNow - lastLog).TotalSeconds >= 1)
{
lastLog = DateTime.UtcNow;
// WKC: expected is the fixed truth established at configuration time, actual reflects the bus as it is right now.
// actual < expected = a mapped slave is not contributing (lost slave / Hot-plug); 0 only means the expected value has not been established, not "no deficit".
ushort expectedWkc = master.Diagnostics.ExpectedWKC;
ushort actualWkc = master.Diagnostics.WKC;
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 运行中, 已使能 {enabledAxisSnapshot}/{ZONE_COUNT} 轴, WKC {actualWkc}/{expectedWkc}"); // [{DateTime.Now:HH:mm:ss}] Running, {enabledAxisSnapshot}/{ZONE_COUNT} axes enabled, WKC {actualWkc}/{expectedWkc}
if (expectedWkc != 0 && actualWkc < expectedWkc)
Console.WriteLine($"WKC 不足 {actualWkc}/{expectedWkc}: 有从站未贡献, 检查掉站/热插拔 (不要下调 expected)"); // WKC short {actualWkc}/{expectedWkc}: a slave is not contributing, check slave loss / hot-plug (do not lower expected)
}
}
}
finally
{
isRunning = false;
try { master.Events.ProcessDataCyclicSync -= OnPdoCycle; }
catch (Exception ex) { Console.WriteLine($"退订周期回调失败: {ex.GetType().Name}: {ex.Message}"); } // Failed to unsubscribe from the cyclic callback: {ex.GetType().Name}: {ex.Message}
// The process image is only usable after passing SafeOp; on early exit (a failure before PreOp) do not touch the PDO mapping
if (master.State >= EcState.SafeOp)
StopAllServos(master);
master.Dispose();
}
}

// EtherCAT cycle callback: advances the CiA 402 state machine per drive + syncs SpeedMatrix (called by the SDK every bus cycle)
void OnPdoCycle(ushort mi)
{
try
{
var m = master;
if (m == null || !isRunning) return;

int enabledAxes = 0;
bool anyFault = false;

// Iterate over drives, fetching each drive's PDO mapping only once and handling both axes together
for (int d = 0; d < DRIVE_COUNT; d++)
{
ref readonly var input = ref m.Slaves[SLAVE_DRIVE_START + d].PDO.InputsMapping<JAWD_Input>();
ref var output = ref m.Slaves[SLAVE_DRIVE_START + d].PDO.OutputsMapping<JAWD_Output>();

output.ModesOfOperation_A = MODE_CSV; // 9 = CSV; written every cycle, no mode switching at runtime
output.ModesOfOperation_B = MODE_CSV;

int axisA = d * 2; // Axis numbering matches the row-major numbering of driveZone
int axisB = axisA + 1;

// The matrix gives the "desired velocity"; the state machine only releases it for OperationEnabled axes and forces the rest to 0,
// Prevents a disabled / handshaking / faulted axis from suddenly moving off a stale velocity.
output.TargetVelocity_A = StepAxis(axisA, input.StatusWord_A,
SpeedMatrix[driveZone[d, 0], driveZone[d, 1]], out ushort cwA);
output.TargetVelocity_B = StepAxis(axisB, input.StatusWord_B,
SpeedMatrix[driveZone[d, 2], driveZone[d, 3]], out ushort cwB);
output.ControlWord_A = cwA;
output.ControlWord_B = cwB;

if ((input.StatusWord_A & 0x006F) == 0x0027) enabledAxes++;
if ((input.StatusWord_B & 0x006F) == 0x0027) enabledAxes++;
if ((input.StatusWord_A & 0x004F) == 0x0008) anyFault = true;
if ((input.StatusWord_B & 0x004F) == 0x0008) anyFault = true;
}

enabledAxisSnapshot = enabledAxes; // Writes snapshots only, printing happens in the main loop (no IO inside the callback)

// Enable wait: set from the real status word (not guessed with Sleep); if an axis is faulted the waiters are released immediately to handle it
if (resetGateCycles > 0) resetGateCycles--; // Do not judge a fault inside the reset pulse window
bool faultBlocksEnable = anyFault && resetGateCycles == 0;
if (!handshakeDone.IsSet)
{
if (faultBlocksEnable) { handshakeFailed = true; handshakeDone.Set(); }
else if (enabledAxes == ZONE_COUNT) handshakeDone.Set();
}
}
catch (Exception ex)
{
// No IO in the RT callback: only accumulate counters + remember the last entry, printing happens in the main loop
cycleErrorText = $"{ex.GetType().Name}: {ex.Message}";
cycleErrorCount++;
}
}

/// <summary>
/// One step of single-axis CiA 402: advances the control word from the status word and returns this cycle's target velocity (rpm).
/// SpeedMatrix velocities are only passed through when OperationEnabled; every other state forces 0 velocity.
/// Control word 0x06->0x07->0x0F; fault reset uses the bit7 rising edge of 0x0006->0x0086 (see ResetFaults).
/// QuickStopActive is the one exception: that state can only be left by 0x0000 (Disable Voltage) back to SwitchOnDisabled.
/// State criteria: running state uses (sw & 0x6F), fault uses (sw & 0x4F) == 0x08.
/// </summary>
int StepAxis(int axis, ushort sw, int requestedSpeed, out ushort cw)
{
if ((sw & 0x004F) == 0x0008) // Fault: wait for a reset, keep sending the stop command
{
if (resetLowCycles[axis] > 0) { resetLowCycles[axis]--; cw = 0x0006; } // Low phase
else if (resetHighCycles[axis] > 0) { resetHighCycles[axis]--; cw = 0x0086; } // High phase (bit7)
else cw = 0x0006;
return 0;
}

resetLowCycles[axis] = 0;
resetHighCycles[axis] = 0;

if (!servoEnableRequested) { cw = 0x0006; return 0; } // Enable not requested: always send Shutdown

switch (sw & 0x006F)
{
case 0x0040: cw = 0x0006; return 0; // SwitchOnDisabled → ReadyToSwitchOn
case 0x0021: cw = 0x0007; return 0; // ReadyToSwitchOn → SwitchedOn
case 0x0023: cw = 0x000F; return 0; // SwitchedOn -> OperationEnabled (velocity still 0 this tick)
case 0x0027: cw = 0x000F; return requestedSpeed; // OperationEnabled: release the velocity
case 0x0007: cw = 0x0000; return 0; // QuickStopActive: only Disable Voltage can return to SwitchOnDisabled
default: cw = 0x0006; return 0; // NotReadyToSwitchOn / unknown: wait for the drive self-test
}
}

/// <summary>
/// Fault reset: only sets the request; the 6040 bit7 0->1 rising edge is generated per cycle by OnPdoCycle.
/// Hold 0x0006 (bit7=0) for 2 ticks first, then 0x0086 (bit7=1 + Shutdown bits) for about 20 ms, then back to 0x0006
/// The status word drives the handshake again. The high-phase tick count is derived from the actual LoopCycle instead of being hard-coded.
/// </summary>
void ResetFaults()
{
if (master == null) return;
int highCycles = Math.Max(2, (int)(20_000_000L / Math.Max(1u, master.LoopCycle)));
for (int axis = 0; axis < ZONE_COUNT; axis++)
{
resetLowCycles[axis] = 2;
resetHighCycles[axis] = highCycles;
}
resetGateCycles = 2 + highCycles; // Reset window: do not judge Fault as an enable failure during it
}

/// <summary>
/// Enable: send a reset pulse to the faulted axes first, then set the "request"; the actual 0x06->0x07->0x0F handshake is done by OnPdoCycle
/// Advance one cycle at a time from the status word. Here we wait on the event the callback sets on real state (bounded timeout) instead of guessing each step with a fixed Sleep.
/// Returning false means a timeout or a faulty axis; the caller must not start the conveyor.
/// </summary>
bool EnableAllServos()
{
handshakeDone.Reset();
handshakeFailed = false;
ResetFaults(); // Give faulted axes a bit7 reset pulse first, then start the handshake
servoEnableRequested = true;

if (!handshakeDone.Wait(TimeSpan.FromSeconds(5)))
{
Console.WriteLine("使能超时: 5s 内未全部进入 OperationEnabled"); // Enable timeout: not all reached OperationEnabled within 5s
return false;
}
if (handshakeFailed)
{
Console.WriteLine("使能中止: 复位后仍有轴处于 Fault, 排除驱动器故障后再调用 EnableAllServos()"); // Enable aborted: axes are still in Fault after the reset, clear the drive faults before calling EnableAllServos()
return false;
}

Console.WriteLine($"{DRIVE_COUNT}台双轴驱动器 ({ZONE_COUNT}轴) 全部使能完成"); // All {DRIVE_COUNT} dual-axis drives ({ZONE_COUNT} axes) are enabled
return true;
}

/// <summary>
/// Stop: ramp the target velocity to 0 first, wait for the actual velocity to decay (bounded 500 ms), then send 0x0006 (Shutdown) to disable.
/// Do not cut torque directly: a fully loaded roller that suddenly freewheels will throw the parcels off.
/// </summary>
void StopAllServos(DarraEtherCAT master)
{
servoEnableRequested = false; // Withdraw the request first: the callback will not release velocity again from here on

for (int d = 0; d < DRIVE_COUNT; d++)
{
ref var output = ref master.Slaves[SLAVE_DRIVE_START + d]
.PDO.OutputsMapping<JAWD_Output>();
output.TargetVelocity_A = 0;
output.TargetVelocity_B = 0;
}

// Wait for the actual velocity to decay to near zero (read the actual velocity from the process image, bounded wait)
var deadline = DateTime.UtcNow.AddMilliseconds(500);
while (DateTime.UtcNow < deadline)
{
bool stopped = true;
for (int d = 0; d < DRIVE_COUNT && stopped; d++)
{
ref readonly var input = ref master.Slaves[SLAVE_DRIVE_START + d]
.PDO.InputsMapping<JAWD_Input>();
if (Math.Abs(input.ActualVelocity_A) > 10 || Math.Abs(input.ActualVelocity_B) > 10)
stopped = false;
}
if (stopped) break;
Thread.Sleep(5);
}

for (int d = 0; d < DRIVE_COUNT; d++)
{
ref var output = ref master.Slaves[SLAVE_DRIVE_START + d]
.PDO.OutputsMapping<JAWD_Output>();
output.ControlWord_A = 0x0006; // Shutdown: keep the voltage, disable (this is not cutting torque)
output.ControlWord_B = 0x0006;
}
Console.WriteLine("所有伺服已停止"); // All servos stopped
}

static void Main(string[] args) => new SingulationController().Run();
}

Vision system usage example:

// The vision algorithm thread writes the speed matrix (rpm) directly
var ctrl = new SingulationController();

// Set the acceleration of one zone
ctrl.SpeedMatrix[2, 3] = 3000; // Row 3, column 4: 3000 rpm

// Set the whole row's deceleration in one go
for (int c = 0; c < 6; c++)
ctrl.SpeedMatrix[1, c] = 500; // Whole row 2: 500 rpm

Complete example code​

This page is a scenario description; the runnable reference is Panasonic_ConveyorSync: multi-servo CiA 402 + DC Sync0 + per-axis PDO output + a monitoring thread independent of the RT callback; it compiles and runs. That sample uses CSP (0x6060 = 8) master/slave synchronization, while this page uses CSV (0x6060 = 9) independent speeds; the difference is that the target quantity moves from 0x607A to 0x60FF. The 36-zone independent speed matrix, the vision decision, and the dual-axis drive (Axis A/B sharing one PDO set) are the parts customized for this page's scenario; the reference project has no matching implementation.

The following projects in this repository also compile, with a one-to-one GitHub directory:

SampleCoverage
Panasonic_ConveyorSyncMulti-axis CiA 402 + Touch Probe, CSP master/slave synchronization
STF-EC_CSP_PPMulti-axis independent control; the number of axes comes from the config.deni scan result
Ezi-SERVO2_CSP_PPSingle-axis CSP / PP, one PDO mapping set per mode
STF-EC_SyncAxisVirtual master axis + electronic gearing (a synchronized-axis scenario, not this page)
HCFA_X3E_QuarterTurnSingle-axis startup sequence reference, 500 µs cycle

For the bit meanings of the control word / status word, the state machine transition criteria, and the 0x6060 value of each mode, see CiA 402 - servo drive protocol.