Skip to main content

Gantry dual-drive differential

One servo on each side of the gantry, both sides following the same virtual master axis at 1:1. The virtual master axis advances once per PDO cycle, and Y1 / Y2 compute their targets from the same master position inside the same callback; Y2 then adds a correction term derived from the actual position difference between the two axes (clamped) to keep the frame from skewing.

This is not "jog each axis independently and write its own 0x607A". Jogging advances the virtual master axis only, so both axes stay synchronized — otherwise each side moves on its own and the frame inevitably skews.

Hardware configuration​

  • Master: Windows 10/11 × 1, with the DarraRT real-time driver
  • Servos: CiA 402 servo drives × 2 (gantry left/right columns, Y1 / Y2 below)
  • Mode: CSP (cyclic synchronous position, 0x6060 = 8)
  • Synchronization: DC Sync0 = 500 µs (default, adjustable 125–10000 µs), equal to LoopCycle
  • Interpolation: 0x60C2 = 50 × 10⁻⁵ s (500 µs), must equal LoopCycle

Axis mapping, DC, 0x60C2 and the steps for entering OP are the same as in Synchronized axes / electronic gearing. This page covers only the differential-synchronization cyclic callback.

0x60C2 is written over SDO after the SafeOp mapping is complete and read back (500 µs → 0x60C2:01 = 50, :02 = -5; 1 ms → 1, -3). If the interpolation cycle does not match the bus cycle, the drive interprets 0x607A on the wrong cadence, which shows up as a larger following error or a scaled velocity.

Performance figures​

  • Control cycle: 500 µs (default, adjustable 125–10000 µs)
  • Master axis advance: += 速度(脉冲/秒) × 周期(秒) per cycle; at 500 µs that is 速度 ÷ 2000
  • Both axis targets are sent in the same frame
  • The correction uses only the current-cycle position difference; there is no cross-cycle planning

How it works​

virtual master axis masterPos += speed (pulses/s) × cycle (s)     // at 500 µs = speed ÷ 2000
Y1 target = Base1 + masterPos
Y2 target = Base2 + masterPos + clamp(k × (Y1 actual − Y2 actual), ±Emax)

At the instant synchronization starts, the actual position of each axis is captured as Base1 / Base2 and the master axis is zeroed — so the starting point is the current actual position and there is no jump. While both axes are not yet in OperationEnabled, the callback re-anchors on every cycle (the master axis does not advance), so the axis that was enabled first does not chase an old Base either. Calling StartSync() / Enable(true) while moving also re-anchors once, and at that moment the targets jump back to the actual positions; to avoid a shock, start synchronization only while both axes are at rest.

k is a small integer gain (for example 1/16, implemented as a bit shift), and Emax limits the correction per cycle to avoid oscillation. When the gear ratio is not 1:1, use electronic gearing; for profile following use electronic cams.

Master/slave semantics: Y1 / Y2 are two independent servo drives, and there is no master/slave frame coupling between the drives — the "master axis" is only a position variable on the master side. 1:1 means the base coupling (both axes receive the same masterPos); trim is a clamped position correction and does not change the gear ratio. When the two axes are rigidly connected, you can also split trim by ½ across both axes so that one side does not carry the whole correction torque permanently.

Unit convention: all position values on this page are computed in the same user unit of 0x6064 / 0x607A (encoder pulses in the example). Once the drive has a gear ratio configured at 0x6091, these two objects express load-side units, so do not multiply by the motor encoder pulse equivalent again; speed (pulses/s) must be converted in the same unit as well.

Soft limits: the differential targets must likewise be checked on the sending side, every cycle. SetSoftLimits(...) in the example below is a local method of this project, not an SDK API; the boundaries come from 0x607D:01 / 0x607D:02 (use the mechanical travel when the drive does not implement soft limits). On an overrun: clamp, latch an alarm, and stop the master axis advance — checking only once in the upper-layer UI misses the case where the gear ratio or the correction pushes a target out of travel.

Why jogging does not write the target position directly​

Writing TargetPosition or the control word from an external thread (a button click) races the PDO callback for the same output mapping: at best the target is occasionally overwritten, at worst a single cycle sends a frame that is half new and half old, and the motor jerks.

The correct approach: the button only changes a volatile master-axis jog request, which the PDO callback consumes inside the cycle. Jogging advances the same virtual master axis, so both axes stay synchronized and the correction still applies.

Code example​

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

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ServoIn
{
public ushort StatusWord; // offset 0: 0x6041 status word
public int ActualPosition; // offset 2: 0x6064 actual position (whole frame 6 bytes)
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ServoOut
{
public ushort ControlWord; // offset 0: 0x6040 control word
public sbyte Mode; // offset 2: 0x6060 operating mode (CSP = 8)
public int TargetPosition; // offset 3: 0x607A target position (whole frame 7 bytes)
}

sealed class GantryDualDrive
{
// List index into master.Slaves (0-based, differs by 1 from the 1-based slave.SlaveNum).
// The bus in this example has only the two gantry servos, so these are 0 / 1; for couplers
// or other slaves, use the actual scan order in config.deni (a wrong index hits another slave).
const int Y1_SLAVE = 0, Y2_SLAVE = 1;
const int Emax = 40; // per-cycle correction limit (pulses)
const int TrimShift = 4; // correction gain k = 1/16 (bit shift)
const uint CycleNs = 500000; // 500 µs (adjustable 125–10000 µs)
const double SpeedPps = 20000.0; // master axis speed (pulses/s); +10 pulses per cycle at 500 µs

readonly DarraEtherCAT _master;

double _masterPos; // virtual master axis position (advanced only in the PDO callback)
int _base1, _base2; // per-axis base captured at the instant synchronization starts
int _reset1, _reset2; // fault reset requests (set by the UI thread with Interlocked, consumed by the PDO callback)

// Soft limits (from 0x607D:01/:02 or the mechanical travel; written by this project's SetSoftLimits, not an SDK API)
int _softMin1 = int.MinValue, _softMax1 = int.MaxValue;
int _softMin2 = int.MinValue, _softMax2 = int.MaxValue;
volatile bool _softLimitLatched; // written by the PDO thread; the upper-layer 50 ms consumer turns it into an alarm and a group stop

volatile bool _enabled; // enable request
volatile bool _syncRunning; // master axis advances automatically
volatile bool _resyncRequested; // start synchronization → snapshot Base and zero the master axis on the next cycle
volatile int _jogDir; // master axis jog direction: +1 / -1 / 0

public GantryDualDrive(DarraEtherCAT master)
{
_master = master;

// Cycle: LoopCycle and DC Sync0 must have the same value; read back and check immediately after setting.
// The state order is fixed INIT → PRE-OP → SAFE-OP → OP; this assumes the connection sequence
// has already performed these steps, and that ConfigureDC is called after SetState(PreOp)
// and before SetState(SafeOp) (for the full sequence see Synchronized axes / electronic gearing).
master.LoopCycle = CycleNs;
if (master.LoopCycle != CycleNs)
throw new Exception($"LoopCycle 设定失败: 请求 {CycleNs}ns, 读回 {master.LoopCycle}ns — 拒绝进入运动链路"); // LoopCycle setup failed: {CycleNs}ns requested, {master.LoopCycle}ns read back — refusing to enter the motion link

for (int i = 0; i < master.SlaveCount; i++)
{
var slave = master.Slaves[i];
if (slave.HasDC && !slave.ConfigureDC(CycleNs)) // Sync0 = 500 µs
throw new Exception($"从站 {slave.SlaveNum} ConfigureDC({CycleNs}ns) 失败 — 拒绝进入运动链路"); // Slave {slave.SlaveNum} ConfigureDC({CycleNs}ns) failed — refusing to enter the motion link
}

// The cyclic PDO callback fires only after the master has entered OP and the PDO thread is running;
// the process image address can change between PreOp and SafeOp, so take the mappings and subscribe only after entering OP.
// Do not take refs during SafeOp and carry them into the callback (see the boundary notes on Slave.ProcessImageGeneration).
master.Events.ProcessDataCyclicSync += OnPdo;
}

// —— The entry points below only set requests; they never write the PDO or the target position directly ——
public void Enable(bool on) { _enabled = on; if (on) _resyncRequested = true; else _syncRunning = false; }
public void StartSync() { _resyncRequested = true; _syncRunning = true; }
public void StopSync() => _syncRunning = false;
public void Jog(int dir) => _jogDir = Math.Sign(dir); // consumed by the PDO callback; call Jog(0) on release
public void ResetFault()
{
Interlocked.Exchange(ref _reset1, 1);
Interlocked.Exchange(ref _reset2, 1);
}

/// <summary> Soft limit boundaries (pulses, in the same user unit as 0x607D:01/:02 or the mechanical travel). </summary>
public void SetSoftLimits(int y1Min, int y1Max, int y2Min, int y2Max)
{
_softMin1 = y1Min; _softMax1 = y1Max;
_softMin2 = y2Min; _softMax2 = y2Max;
}

/// <summary> Clear the soft limit latch (check the mechanical travel and the position before calling StartSync again). </summary>
public void ClearSoftLimit() => _softLimitLatched = false;

public bool SoftLimitLatched => _softLimitLatched;

static int Clamp(int value, int min, int max)
=> value < min ? min : (value > max ? max : value);

void OnPdo(ushort masterIndex)
{
ref readonly var y1In = ref _master.Slaves[Y1_SLAVE].PDO.InputsMapping<ServoIn>();
ref readonly var y2In = ref _master.Slaves[Y2_SLAVE].PDO.InputsMapping<ServoIn>();
ref var y1Out = ref _master.Slaves[Y1_SLAVE].PDO.OutputsMapping<ServoOut>();
ref var y2Out = ref _master.Slaves[Y2_SLAVE].PDO.OutputsMapping<ServoOut>();

int y1Act = y1In.ActualPosition;
int y2Act = y2In.ActualPosition;
ushort y1Sw = y1In.StatusWord;
ushort y2Sw = y2In.StatusWord;
bool bothReady = _enabled && IsOperationEnabled(y1Sw) && IsOperationEnabled(y2Sw);

// ① Start of synchronization / handshake in progress: snapshot both actual positions as Base and zero the master axis (done atomically inside the same callback).
// While not in OperationEnabled, re-anchor on every cycle: the master axis does not advance, but the target always equals the actual,
// so an axis that is enabled later does not jump toward an old Base.
if (_resyncRequested || !bothReady)
{
_resyncRequested = false;
_masterPos = 0;
_base1 = y1Act;
_base2 = y2Act;
}

// ② Advance the virtual master axis: speed (pulses/s) × cycle (s) — at 500 µs that is speed ÷ 2000.
// Advance only while both axes are in OperationEnabled; otherwise, if one axis drops out of OP while the master axis keeps running,
// its target catches up in one go the moment it recovers → shock / jump.
// Once the soft limit latches, neither the master axis nor jogging advances until the upper layer calls ClearSoftLimit.
double step = SpeedPps * (CycleNs / 1000000000.0);
double prevMasterPos = _masterPos;
if (bothReady && !_softLimitLatched)
{
if (_syncRunning) _masterPos += step;
if (_jogDir != 0) _masterPos += _jogDir * step; // jogging advances the same master axis → both axes stay synchronized
}
double masterPos = _masterPos;

// ③ Compute both targets inside the same callback and commit them together in the same PDO frame
// (MutexProtection defaults to true, so no extra locking is needed)
int y1Target = _base1 + (int)Math.Round(masterPos);

int diff = y1Act - y2Act; // position difference this cycle: positive when Y1 leads
int trim = diff >> TrimShift; // k = 1/16; a positive value increases the Y2 target to catch up with Y1
if (trim > Emax) trim = Emax;
if (trim < -Emax) trim = -Emax;

int y2Target = _base2 + (int)Math.Round(masterPos) + trim; // 1:1 + correction

// ③b Soft limits are checked on the sending side every cycle: clamp on overrun, latch the alarm, stop the master axis, and both axes stop at the limit.
if (y1Target < _softMin1 || y1Target > _softMax1 ||
y2Target < _softMin2 || y2Target > _softMax2)
{
_softLimitLatched = true;
_syncRunning = false;
_masterPos = prevMasterPos; // roll back this cycle's increment so that clearing the latch does not cross the limit in one move
y1Target = Clamp(y1Target, _softMin1, _softMax1);
y2Target = Clamp(y2Target, _softMin2, _softMax2);
}

// ④ Each axis runs the full CiA402 state machine; when not enabled / faulted / NotReady, target = actual
bool reset1 = Interlocked.Exchange(ref _reset1, 0) != 0;
bool reset2 = Interlocked.Exchange(ref _reset2, 0) != 0;
StepAxis(ref y1Out, y1Sw, y1Act, y1Target, _enabled, reset1);
StepAxis(ref y2Out, y2Sw, y2Act, y2Target, _enabled, reset2);
}

// Status word masks: 0x6F for the running state, 0x4F for fault / not ready.
static bool IsFault(ushort sw) => (sw & 0x4F) == 0x08;
static bool IsNotReady(ushort sw) => (sw & 0x4F) == 0x00;
static bool IsSwitchOnDisabled(ushort sw) => (sw & 0x6F) == 0x40;
static bool IsReadyToSwitchOn(ushort sw) => (sw & 0x6F) == 0x21;
static bool IsSwitchedOn(ushort sw) => (sw & 0x6F) == 0x23;
static bool IsOperationEnabled(ushort sw) => (sw & 0x6F) == 0x27;
static bool IsQuickStopActive(ushort sw) => (sw & 0x6F) == 0x07; // a state of its own, not an "enable failure"

// Single axis CiA402: 0x06 → 0x07 → 0x0F; a fault reset sends one cycle of 0x86 in the process data; at all other times always 0x0006.
// The only exception is QuickStopActive: only 0x0000 (Disable Voltage) returns to SwitchOnDisabled,
// and there is no 0x0006 transition from that state, so sending 0x0006 forever leaves the axis stuck.
// In any non-running state the target position equals the current actual position (no jump).
static void StepAxis(ref ServoOut output, ushort sw, int actPos, int runTarget,
bool allowRun, bool resetPending)
{
output.Mode = 8; // always CSP
ushort cw = 0x0006; // default: a real stop command (not 0x0000)
int target = actPos; // default target = actual

if (resetPending && IsFault(sw)) // fault reset: send one cycle of 0x86 only to an axis that is really in Fault; the next cycle returns to 0x0006 automatically
{
cw = 0x86;
}
else if (IsFault(sw)) // still faulted (the reset request has not taken effect yet): wait for [Fault reset]
{
}
else if (IsQuickStopActive(sw)) // QuickStopActive: the only exit is Disable Voltage
{
cw = 0x0000;
}
else if (!allowRun) // not enabled: target = actual
{
}
else if (IsNotReady(sw)) // NotReadyToSwitchOn: wait
{
}
else if (IsSwitchOnDisabled(sw)) // Shutdown
{
cw = 0x06;
}
else if (IsReadyToSwitchOn(sw)) // Switch On
{
cw = 0x07;
}
else if (IsSwitchedOn(sw)) // Enable Operation
{
cw = 0x0F;
}
else if (IsOperationEnabled(sw)) // running state: only here is the synchronized target used
{
// CSP holds 0x000F; bit4 (0x0010) is the PP/HM NewSetpoint and is undefined in CSP,
// never write 0x001F (continuous writes make a measured HCFA X3E report 0x7500).
cw = 0x0F;
target = runTarget;
}

output.ControlWord = cw;
output.TargetPosition = target;
}
}

Before entering OP, set TargetPosition on both axes to the actual position at that moment (target = actual) and use 0x0006 as the control word. Then snapshot Base1 / Base2 and zero the master axis when synchronization starts.

Jerk red lines: in CSP never write 0x001F; test the running state with 0x6F and the fault state with 0x4F; when not enabled / faulted / NotReady, target = actual; the fault reset sends one cycle of 0x86 in the process data; QuickStopActive can only be left with 0x0000; soft limits are checked on the sending side every cycle; both axis targets must be written inside the same callback; never use Thread.Sleep / while as the cycle. A single-axis commissioning example is not the same as synchronized axes.

For multi-axis gear ratios use Synchronized axes / electronic gearing; for cams use multi-axis electronic cams.

Complete example code​

This page describes a scenario; the runnable reference is STF-EC_SyncAxis: multiple axes share one virtual master axis, the default is 500 µs (adjustable 125–10000 µs), DC Sync0 equals LoopCycle, and each axis is issued inside the same ProcessDataCyclicSync callback. It compiles and runs. The "position-difference correction + clamp" on this page is the part customized for gantry skew prevention; the reference project uses fixed-ratio electronic gearing and has no correction term.

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

SampleCoverage
STF-EC_SyncAxisVirtual master axis + electronic gearing (default 500 µs, adjustable 125–10000 µs)
STF-EC_ECamMulti-axis electronic cams, DC Sync0 1 ms
STF-EC_CSP_PPMulti-axis stepper CSP / PP; the number of axes comes from the config.deni scan result