Synchronized axes / electronic gearing
STF-EC stepper drive synchronized-axis motion control example built on the Darra EtherCAT Master class library (WinForms UI).
Several axes follow the same virtual master axis, each at its own gear ratio (Ratio).
- Ratio 1:1: every axis "maps the same data point at the same instant", and motion is identical.
- Ratio ≠ 1: electronic gearing — the axes are coupled at a fixed ratio.
- The operating mode is always CSP (cyclic synchronous position, Mode=8).
The complete source for this example (WinForms project + config.deni):
https://github.com/DarraTechnology/Ethercat_Master/tree/main/Windows/CSharp/STF-EC_SyncAxis
Hardware configuration
- Master: Windows 10 × 1 + Intel i5 × 1
- Stepper drives: MOONS' (Shanghai AMP&MOONS' Automation) STF-EC EtherCAT stepper drive × 5 + stepper motor × 5
| Item | Value |
|---|---|
| Vendor | MOONS' Shanghai AMP&MOONS' Automation |
| VendorId | 0x00000168 |
| ProductCode | 0x02 |
| Protocol | CoE (CiA 402 Profile) |
| Synchronization | DC Sync0 = 500 µs (default, adjustable 125–10000 µs) |
| Axis count | Determined by the config.deni scan (the supplied configuration has 5 axes, PhysAddr 0x1001~0x1005) |
Same hardware and the same
config.denias theSTF-EC_CSP_PPexample; it can be reused directly.
Motion parameters
- Control mode: CSP (cyclic synchronous position, Mode=8) — synchronized coupling uses CSP only
- Pulses per revolution: read per axis over SDO at connect time (
0x2604:00Steps per Rev, falling back to0x608F:01); there is no constant to edit. If neither can be read the CPR is unknown: the position column shows raw counts only and no angle conversion is done (10000 is never assumed) - Position unit:
0x607A(target position) and0x6064(actual position) use the same drive position unit — the user unit obtained after the encoder resolution0x608Fis scaled by the gear ratio0x6091and the feed constant0x6092, not raw encoder counts. This page treats the "pulse" as the position unit: 1 pulse equals 1 encoder count only when0x6091 = 1:1; if0x6091has been changed, fold the gear ratio in first, otherwise both the pulses-per-revolution value and the gear ratio are off by the same factor. Swapping the numerator/denominator of0x6091together with the0x607Epolarity decides the positive direction of the axis; a negative ratio only adds on top of that. - Control cycle: 500 µs default, adjustable 125–10000 µs (in 25 µs steps, set before connecting)
- Interpolation time base: if the drive uses
0x60C2(Interpolation Time Period) for CSP interpolation,0x60C2:01(cycle value, UINT8, 1–255) and0x60C2:02(decimal exponent, INT8) must match this cycle: cycle = value × 10^exponent. 500 µs → value50, exponent-5; 1 ms → value1, exponent-3. 500 µs must not be written as value 500 with exponent -6 —0x60C2:01is only 1 byte and cannot hold 500. Together withLoopCycleandConfigureDCthese are three settings of the same cycle; when the cycle changes, change them together. - Virtual master axis speed: set by the user (pulses/s). The advance per cycle = speed (pulses/s) × cycle (s); at 500 µs that is speed ÷ 2000. Accumulate the step in floating point: at 500 µs and 1000 pulses/s there are only 0.5 pulses per cycle, and rounding to 0 would stop the master axis completely.
- Ratio range: any real number (
1.0fully synchronized /2.02× the master axis /0.5half /-1.0reverse at equal speed)
Performance figures
- Control cycle: 500 µs default (
LoopCycle= DC Sync0 = the samecycleNs, adjustable 125–10000 µs) - Multi-axis synchronization: every slave axis is locked to the same virtual master axis phase, and at a 1:1 ratio all axes advance by exactly the same position increment. Synchronization uses DC Sync0 as the time base; a slave dropping out of OP triggers an alarm for that axis and a group stop, and synchronization must be started again after recovery.
- Position accuracy: ±1 pulse quantization error on the issued target position (mechanical positioning accuracy also depends on drive interpolation, encoder resolution and mechanical stiffness)
- Smooth start: at the instant synchronization starts, each axis actual position is captured as its base, so there is no jump
Application scenario
Electronic gearing / synchronized axes are used where industrial machinery needs multiple axes coupled at strict ratios. Typical cases:
- Unwind/rewind synchronization: the unwind and rewind axes are synchronized by line-speed ratio, keeping tension constant.
- Gantry dual-drive synchronization: the drive axes on both sides of the gantry must be strictly synchronized at 1:1 to keep the frame from skewing and jamming.
- Slitter: the main roller and several slitting knife rollers are coupled by gear ratio.
- Print register: several color-unit rollers feed the web in synchronization at fixed ratios to hold register accuracy.
Set a different ratio on each axis and the proportional coupling is visible to the eye.
How it works
Virtual master axis
This example needs no physical "master axis" hardware. A software counter acts as the virtual master axis, and every axis follows that counter:
- Automatic advance: after Start Sync is pressed, the master axis position advances by
+= 速度 × 周期every PDO cycle (500 µs default). For example, at 80000 pulses/s and a 500 µs cycle it advances by 40 pulses per cycle (80000 ÷ 2000). - Manual jog: hold "◀ Master-" / "Master+ ▶" to push the master axis position forward or back directly — convenient for manual alignment and for watching the proportional motion.
- Snapshot at start: when Start Sync is pressed, the PDO thread re-snapshots each axis current actual position as the base
Baseand zeroes the master axis, so motion starts smoothly from the current position without a jump.
Each axis follows at its gear ratio
The target position of every real axis is computed from the same virtual master axis position masterPos; the only difference is each axis gear ratio Ratio:
Target position = Base + round(masterPos × Ratio)
Ratio meanings:
1.000— every axis gets exactly the same target increment → "the same data point mapped at the same instant"; all axes step together2.000— this axis moves 2× the master axis (the master turns 1 revolution, the slave turns 2 revolutions)0.500— this axis moves half the master axis-1.000— this axis follows in the opposite direction at equal speed
The statement that the master turns 1 revolution while the slave turns 2 holds only if the master and slave axes use the same position unit (
0x6091gear ratio and pulses per revolution match). The ratio is a ratio between position units, not a mechanical revolution ratio; when the two axes have different CPR, convert the mechanical revolution ratio into a position-unit ratio before enteringRatio.
Electronic gearing is the linear special case of an electronic cam: an electronic cam makes the slave axis follow the master through a master/slave position curve; when that curve degenerates into a straight line (constant slope = the gear ratio), it is electronic gearing.
System architecture
Code example
PDO struct definitions
The authority for the PDO layout is the default mapping in the EtherCAT Slave Information (ESI) (STF-EC: 29 bytes of output, 35 bytes of input). The field order must match the PDO entries byte for byte and must not be rearranged; 0x1C12/0x1C13 are used only to verify the actual assignment.
using System.Runtime.InteropServices;
/// <summary>
/// STF-EC stepper drive output PDO (RxPDO) = 29 bytes (0x1600~0x1603)
/// A synchronised axis always uses CSP, so ModesOfOperation is always = 8.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct STF_Output // 29 bytes
{
// ---- 0x1600 ----
public ushort ControlWord; // 0x6040 control word (CiA402 state machine)
public sbyte ModesOfOperation; // 0x6060 mode of operation (a synchronised axis is always CSP=8)
public int TargetPosition; // 0x607A target position (pulses) <- sent every cycle
// ---- 0x1601 ----
public uint ProfileVelocity; // 0x6081 profile velocity (not used in this example)
public uint ProfileAcceleration; // 0x6083 profile acceleration
public uint ProfileDeceleration; // 0x6084 profile deceleration
// ---- 0x1602 ----
public int TargetVelocity; // 0x60FF target velocity (used in PV mode, not used in this example)
// ---- 0x1603 ----
public uint PhysicalOutputs; // 0x60FE:1 digital outputs
public ushort TouchProbeFunction; // 0x60B8 probe function
}
/// <summary>
/// STF-EC stepper drive input PDO (TxPDO) = 35 bytes (0x1A00~0x1A03)
/// Note: in this PDO the error code comes first and the status word second.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct STF_Input // 35 bytes
{
// ---- 0x1A00 ----
public ushort ErrorCode; // 0x603F error code
public ushort StatusWord; // 0x6041 status word (CiA402 state machine)
public sbyte ModesOfOperationDisplay; // 0x6061 displayed mode of operation
// ---- 0x1A01 ----
public int PositionActualValue; // 0x6064 actual position (pulses) <- used for the following error / Base
// ---- 0x1A02 ----
public int VelocityActualValue; // 0x606C actual velocity (pulses/s)
// ---- 0x1A03 ----
public uint DigitalInputs; // 0x60FD digital inputs
public ushort TouchProbeStatus; // 0x60B9 probe status
public int TouchProbe1PosValue; // 0x60BA probe 1 rising-edge position
public int TouchProbe1NegValue; // 0x60BB probe 1 falling-edge position
public int TouchProbe2PosValue; // 0x60BC probe 2 rising-edge position
public int TouchProbe2NegValue; // 0x60BD probe 2 falling-edge position
}
Connecting and DC synchronization
CSP synchronized coupling requires a new target position to be issued precisely every PDO cycle. The connection phase must therefore do four things first:
- Set the cycle:
LoopCycleand DC Sync0 use the samecycleNs, and the value is read back and checked. - Verify the PDO assignment against the ESI default mapping (
0x1C12/0x1C13read-only check, no blind remapping). - Enable DC (Distributed Clocks); Sync0 has the same value as
LoopCycle. - Initialize the target position to the actual position (to prevent a jump at power-up).
Only the key steps are shown below; boilerplate such as try/catch and CancellationToken cancellation checks is omitted.
// 1) Build the master: load config.deni, start the auto-startup flow
var buildResult = new DarraEtherCAT()
.SetENI(deniPath)
.EnableAutoStartup()
.Build();
if (!buildResult.Success || buildResult.Master == null)
throw new Exception($"主站初始化失败: {buildResult.Message}"); // Master initialization failed: {buildResult.Message}
DarraEtherCAT master = buildResult.Master;
int slaveCount = master.SlaveCount; // Axis count = the number of slaves actually scanned
if (slaveCount <= 0)
throw new Exception("未扫描到任何从站 — 拒绝进入运动链路"); // No slaves were found by the scan — refusing to enter the motion link
// 2) Cycle time: set LoopCycle and read it back to verify before any state transition.
// Readback != requested -> refuse to enter the motion chain (no "good enough" degradation).
uint cycleNs = 500000; // Default 500 µs; adjustable from 125000 to 10000000 (125~10000 µs)
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
// 3) Enter PreOp: SM2 is not active yet, so do the PDO assignment check / CSP mode setting / DC configuration
// The state transition returns bool: on failure it must stop here; "did not reach PreOp" must never be treated as "reached PreOp" and SDO writes continued
if (!master.SetState(EcState.PreOp))
throw new Exception("进入 PreOp 失败 — 拒绝继续配置 PDO / CSP / DC"); // Failed to enter PreOp — refusing to continue configuring PDO / CSP / DC
// Match the drive profile per axis by VendorId/ProductCode (the profile carries the expected ESI PDO assignment); an identity mismatch refuses the connection outright
for (int i = 0; i < slaveCount; i++)
{
var slave = master.Slaves[i];
// Exact match against the identity profile (Vendor/Product/Rev); a miss = refuse to connect and emit no motion commands
var profile = DriveProfiles.MatchByVendorProduct(slave.VendorId, slave.ProductId);
if (profile == null) throw new Exception($"轴{i + 1} 身份不符, 拒绝连接"); // Axis{i + 1} identity mismatch, connection refused
if (!DriveProfiles.RevisionAccepted(profile, slave.RevId))
throw new Exception($"轴{i + 1} 修订号 0x{slave.RevId:X8} 不在档案已知修订集内, 拒绝连接"); // Axis{i + 1} revision number 0x{slave.RevId:X8} is not in the profile's known revision set, connection refused
// 4) PDO layout authority = the ESI default mapping (HCFA 9/25 B, Ezi-SERVO2 12/22 B, STF-EC 29/35 B).
// 0x1C12/0x1C13 are only for verifying the actual assignment; do not blindly rewrite or remap - one wrong remap entry will break the slave configuration.
VerifyPdoAssignment(slave, 0x1C12, profile.ExpectedRxPdo, i); // Read-only check, see below
VerifyPdoAssignment(slave, 0x1C13, profile.ExpectedTxPdo, i);
// 5) CSP mode: 0x6060 is in the PDO mapping -> write 8 frame by frame at runtime;
// Not in the mapping (such as the Ezi CSP mapping) -> here, in PreOp, write 8 with SDO and read it back to verify.
// Whether it is in the mapping is decided by the profile's PDO layout (ModeOff < 0 means it is not in the mapping).
if (profile.EsiLayout.ModeOff < 0)
{
var coe = slave.CoE ?? throw new Exception($"轴{i + 1} 无 CoE 协议实例, 无法设 CSP 模式"); // Axis{i + 1} has no CoE protocol instance, CSP mode cannot be set
if (!coe.SDOWrite(0x6060, 0, new byte[] { 8 }, out SdoWriteResult writeResult) || !writeResult.Ok)
throw new Exception($"轴{i + 1} 0x6060 写 8 失败: Error={writeResult.Error}, AbortCode=0x{writeResult.AbortCode:X8}"); // Axis{i + 1} failed to write 8 to 0x6060: Error={writeResult.Error}, AbortCode=0x{writeResult.AbortCode:X8}
if (ReadSdoI8(slave, 0x6060, 0) != 8)
throw new Exception($"轴{i + 1} 0x6060 读回 ≠ 8, CSP 模式未生效"); // Axis{i + 1} 0x6060 read back ≠ 8, CSP mode is not in effect
}
// 6) DC Sync0 = the same cycleNs (the time base for CSP cyclic synchronisation, must equal LoopCycle)
// Returning false = DC is not configured on that slave; CSP synchronisation depends on it, so refuse to connect honestly instead of degrading and continuing.
if (slave.HasDC && !profile.SkipManualDcConfig && !slave.ConfigureDC(cycleNs))
throw new Exception($"轴{i + 1} ConfigureDC({cycleNs}ns) 失败 — CSP 同步依赖 DC Sync0, 拒绝连接"); // Axis{i + 1} ConfigureDC({cycleNs}ns) failed — CSP synchronization depends on DC Sync0, connection refused
// Ezi-SERVO2 exception (profile SkipManualDcConfig): skip manual ConfigureDC - arming SYNC0 too early leaves a gap before OP that trips the sync error watchdog
// (latch 0x7500); SetState(OP)'s AutoStartup arms SYNC0 and sets 0x10F1:02 to 65535.
}
// 7) Enter SafeOp
if (!master.SetState(EcState.SafeOp))
throw new Exception("进入 SafeOp 失败 — 拒绝进 OP"); // Failed to enter SafeOp — refusing to enter OP
// 8) PDO size self-check: compare the byte count measured from the process image against the ESI layout to catch a mis-mapping
// When the device OD cannot give the PDO mapping struct, this step is the last gate.
int expOut = Marshal.SizeOf<STF_Output>(); // 29
int expIn = Marshal.SizeOf<STF_Input>(); // 35
for (int i = 0; i < slaveCount; i++)
{
if (master.Slaves[i].OutputsByteCount != expOut ||
master.Slaves[i].InputsByteCount != expIn)
throw new Exception($"轴{i + 1} PDO 尺寸不符 (ESI 布局 29/35B), 拒绝进 OP"); // Axis{i + 1} PDO size mismatch (ESI layout 29/35B), refusing to enter OP
}
// 9) Initialise each axis before entering OP: stop command + CSP mode + target position = current actual position (prevents a power-on jump)
for (int i = 0; i < slaveCount; i++)
{
ref readonly var input = ref master.Slaves[i].PDO.InputsMapping<STF_Input>();
ref var output = ref master.Slaves[i].PDO.OutputsMapping<STF_Output>();
output.ControlWord = 0x0006; // The real stop command (not 0x0000: bit2 is active low and would hold QuickStop)
output.ModesOfOperation = 8; // CSP
output.TargetPosition = input.PositionActualValue; // Target = actual, zero jump
}
// 10) Enter OP and start cyclic communication (if this fails nothing moved; it must not be treated as success)
if (!master.SetState(EcState.OP))
throw new Exception("进入 OP 失败 — 运动链路未建立"); // Failed to enter OP — the motion link is not established
The PDO assignment check is read-only, never a write. If the values can be read, compare them entry by entry against the ESI expectations; a failed read is not treated as a failure (some vendors' device object dictionaries do not expose the PDO structure) — continue with the ESI layout and rely on the process image byte count as the fallback:
// Read-only check: compare the assignment counts of 0x1C12/0x1C13 and every entry against what the ESI expects
void VerifyPdoAssignment(Slave slave, ushort assignIndex, ushort[] esiExpected, int axisNo)
{
if (!TrySdoReadU32(slave, assignIndex, 0, out uint count))
return; // The device OD has no mapping struct -> continue with the ESI
if (count != esiExpected.Length)
throw new Exception($"轴{axisNo + 1} 0x{assignIndex:X4} 分配数量不符: 实际 {count}, ESI 期望 {esiExpected.Length}"); // Axis{axisNo + 1} 0x{assignIndex:X4} assignment count mismatch: actual {count}, ESI expects {esiExpected.Length}
for (int k = 0; k < esiExpected.Length; k++)
{
if (!TrySdoReadU32(slave, assignIndex, (byte)(k + 1), out uint actual))
continue; // A single item cannot be read -> skip it
if ((ushort)actual != esiExpected[k])
throw new Exception($"轴{axisNo + 1} 0x{assignIndex:X4}:{k + 1:X2} 不符: 实际 0x{actual:X4}, ESI 期望 0x{esiExpected[k]:X4}"); // Axis{axisNo + 1} 0x{assignIndex:X4}:{k + 1:X2} mismatch: actual 0x{actual:X4}, ESI expects 0x{esiExpected[k]:X4}
}
}
TrySdoReadU32/ReadSdoI8are thin wrappers aroundslave.CoE.SDORead/SDOWrite: a write always checks the result code and a read always checks the abort code. Report failures as they are; never treat a failed read as 0 and carry on.
Electronic gearing ratio calculation
All the math for synchronized axes is a single line. The target position of each slave axis comes from three parts added (multiplied) together:
- the base position
Basecaptured when synchronization starts. - the virtual master axis position
masterPos. - the gear ratio of that axis,
Ratio.
That is: target position = Base + masterPos × Ratio.
// Core formula (single axis, single cycle):
// Target position = Base + round(masterPos x Ratio)
a.CurrentTarget = a.Base + (int)Math.Round(masterPos * a.Ratio);
Base: the actual position of that axis snapshotted at the instant synchronization starts — motion begins smoothly from the current point with no jump.masterPos: the virtual master axis position; every axis uses the same value → all axes are locked to the same phase.Ratio: the gear ratio of that axis. At1.0every axis gets the same target increment (the same data point mapped at the same instant); with≠1.0this is electronic gearing and the axes spread apart in proportion.
Electronic gearing is the linear special case of an electronic cam: degenerate the cam master/slave position curve into a straight line with slope =
Ratio, and the formula reduces from a curve lookup to a single multiplication.
CSP cyclic following control
The SDK PDO cyclic callback runs once per bus cycle (500 µs default). Each callback does two things:
- advance the virtual master axis once (
masterPos += 速度 × 周期). - then compute the target position for each axis and issue it inside the same callback.
Every axis also runs the CiA 402 enable handshake (0x06 → 0x07 → 0x0F). While the handshake is incomplete, or the axis is faulted or in an unrecognized state, the control word is 0x0006 (a real stop command) and the target position always equals the actual position (so there is no jump). The only exception is QuickStopActive ((sw & 0x6F) == 0x07): it can only be left by 0x0000 (Disable Voltage) returning to SwitchOnDisabled, and sending 0x0006 leaves the axis stuck in that state permanently.
Real-time control must hang off the SDK PDO cyclic callback (
ProcessDataCyclicSync) and be hard-synchronized by the bus cycle (DC Sync0 =cycleNs, 500 µs default).Never spin with
Thread.Sleepin application code. That has three problems: an indeterminate cycle, large jitter and loss of synchronization with DC — it is not deterministic real-time control.
// Pulses per revolution is never hard-coded: read per axis over SDO at connect time (0x2604:00 -> fall back to 0x608F:01); unreadable = CPR unknown and no angle conversion (never guess 10000)
const int JOG_MASTER_PPS = 40000; // Master axis manual jog velocity (pulses/s)
uint _cycleNs = 500_000; // Set at connect time; the same value as LoopCycle / DC Sync0
double _masterPos = 0.0; // Virtual master axis position (pulses; the fraction is kept and only rounded when computing the target)
volatile int _masterPps = 80000; // Master axis velocity (pulses/s), written by the UI thread; e.g. 80000 pulses/s at a 500 µs cycle = 40 pulses per tick
volatile int _jogPps = JOG_MASTER_PPS;
volatile bool _syncRunning = false; // Whether it advances automatically
volatile bool _resyncRequested = false; // Start synchronisation -> re-snapshot Base next cycle + zero the master axis
volatile int _jogMasterDir = 0; // Master axis manual jog direction: +1 / -1 / 0
// Velocity (pulses/s) -> step per cycle: always derived as "velocity x cycle",
// Never hard-code fixed divisors like 8000 / 2000 - when the cycle changes the step must be recomputed.
// The return value is a double and is not rounded: at 500 µs and 1000 pulses/s each tick is only 0.5 pulses, and rounding to 0 would stop the master axis advancing entirely at low speed;
// Position is accumulated in double; rounding happens only at the "compute this tick's target position" step.
static double StepFromSpeed(int speedPps, uint cycleNs)
=> speedPps * (cycleNs / 1000000000.0);
// Real-time control is attached to the SDK's PDO cycle callback - hard-synchronised by the bus cycle (DC Sync0 500 µs),
// Runs per cycle in the SDK's PDO thread context. Never use Thread.Sleep / a while spin.
master.Events.ProcessDataCyclicSync += OnPdoCycle;
/// <summary>
/// PDO cycle callback: the SDK calls it automatically once per bus cycle (LoopCycle = 500 µs by default),
/// Advance the virtual master axis and let each axis follow through the gear ratio (driven by DC Sync0).
/// Parameter mi = master index.
/// </summary>
void OnPdoCycle(ushort mi)
{
var m = master;
if (m == null) return;
var arr = axes; // Reference snapshot (volatile field)
// ① Start synchronisation: re-snapshot each axis Base, zero the master axis (done inside the PDO callback, so it is atomic)
if (_resyncRequested)
{
_resyncRequested = false;
_masterPos = 0;
for (int i = 0; i < arr.Length; i++)
{
ref readonly var input = ref m.Slaves[arr[i].SlaveIndex].PDO.InputsMapping<STF_Input>();
arr[i].Base = input.PositionActualValue; // Based on the current actual position
arr[i].CurrentTarget = input.PositionActualValue;
}
}
// ② Advance the virtual master axis (auto sync + manual jog); the step is computed from "velocity × cycle" instead of caching an integer step
if (_syncRunning) _masterPos += StepFromSpeed(_masterPps, _cycleNs);
int jog = _jogMasterDir;
if (jog != 0) _masterPos += jog * StepFromSpeed(_jogPps, _cycleNs);
double masterPos = _masterPos;
// ③ Each axis follows the same virtual master axis through its gear ratio
// Write each axis target position consecutively inside one callback -> commit them all in one PDO frame
// (MutexProtection defaults to true, no extra locking needed).
for (int i = 0; i < arr.Length; i++)
{
var a = arr[i];
ref readonly var input = ref m.Slaves[a.SlaveIndex].PDO.InputsMapping<STF_Input>();
ref var output = ref m.Slaves[a.SlaveIndex].PDO.OutputsMapping<STF_Output>();
StepSync(a, masterPos, in input, ref output);
}
// There are also alarm detections and group-stop logic for following errors / dropping out of OP / drive faults; see the source for details.
}
// Status word mask: always judge the running state with 0x6F and the fault state with 0x4F.
// Do not use 0x4F to test for the running state - the bit4/bit5 difference would be misread as "not running".
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 separate state, not an "enable failure"
// Re-baselining while disabled / handshaking: the anchor makes "target == actual" true instantly.
// If Base = actual position directly, the target jumps by masterPos x Ratio the moment enable lands whenever masterPos != 0.
static void ReanchorBaseBumpless(AxisController a, double masterPos, int actPos)
=> a.Base = actPos - (int)Math.Round(masterPos * a.Ratio);
/// <summary>
/// Single-axis CSP stepping: CiA402 enable handshake (0x06->0x07->0x0F); once enabled it follows the virtual master axis through the gear ratio.
/// Default output = stop command 0x0006 + target = current actual position; the gear-ratio target is only released when OperationEnabled and the target is inside the soft limits.
/// QuickStopActive is the one state where 0x0000 (Disable Voltage) must be sent - it is the only transition out of that state.
/// The fault reset 0x86 is sent as one tick inside this PDO callback (bit7 rising edge, bit2 held at 1).
/// </summary>
void StepSync(AxisController a, double masterPos, in STF_Input input, ref STF_Output output)
{
output.ModesOfOperation = 8; // Always CSP
ushort sw = input.StatusWord;
int actPos = input.PositionActualValue;
ushort cw = 0x0006; // Default: the real stop command (not 0x0000)
// Write "target = actual" back unconditionally first; only the OperationEnabled branch overwrites it later.
// Without this line, QuickStopActive / an unrecognised state keeps the previous tick's stale target and the axis charges at it hard the moment enable returns.
a.CurrentTarget = actPos;
output.TargetPosition = actPos;
if (a.FaultReset) // Fault reset: low phase 0x0006 -> high phase 0x0086, forming a bit7 rising edge
{
// CiA 402 clears Fault on a bit7 rising edge only; if the drive also requires a clean bit2=1 edge (such as the HCFA X3E),
// Composed of 0x0006 (bit7=0, bit2=1) -> 0x0086 (bit7=1, bit2=1) over two ticks, see ResetFaults.
// Never write 0x0000 in any state other than QuickStopActive: bit2 is active low and would hold QuickStop, and in CSP the drive then reports 0x7500.
cw = 0x86;
a.FaultReset = false;
}
else if (IsFault(sw)) // Fault state: wait for [all fault resets], the target holds the actual position
{
}
else if (!a.ServoEnabled) // Disabled: target = actual
{
ReanchorBaseBumpless(a, masterPos, actPos);
}
else if (IsNotReady(sw)) // NotReadyToSwitchOn: wait, target = actual
{
ReanchorBaseBumpless(a, masterPos, actPos);
}
else if (IsSwitchOnDisabled(sw)) // Shutdown
{
cw = 0x06;
ReanchorBaseBumpless(a, masterPos, actPos);
}
else if (IsReadyToSwitchOn(sw)) // Switch On
{
cw = 0x07;
ReanchorBaseBumpless(a, masterPos, actPos); // Re-anchor during the handshake too: the master phase keeps advancing, so without a re-anchor it jumps masterPos x Ratio the instant enable lands
}
else if (IsSwitchedOn(sw)) // Enable Operation
{
cw = 0x0F;
ReanchorBaseBumpless(a, masterPos, actPos);
}
else if (IsQuickStopActive(sw)) // QuickStopActive: only Disable Voltage can exit
{
// CiA 402 has only two exits from QuickStopActive: bit1=0 (Disable Voltage, 0x0000) or bit2=0 (Quick Stop)
// -> SwitchOnDisabled. Shutdown 0x0006 has bit1=bit2=1, which is undefined for that state - sending 0x0006 forever wedges it.
cw = 0x0000;
}
else if (IsOperationEnabled(sw))
{
// —— synchronised axis core: target = base + master position × gear ratio ——
// Gear ratio 1:1 -> every axis has the same target increment (one data point maps to all); gear ratio != 1 -> electronic gear.
int desired = a.Base + (int)Math.Round(masterPos * a.Ratio);
// The soft limit is checked **every cycle on the command side**: with a gear ratio above 1, the master axis pushed to the end of travel, or a drifting base,
// Checking it only in the upper-layer UI will miss cases. Exceeding the limit -> clamp + latch the alarm + stop the master axis advance (all followers stop together at the limit).
if (desired < a.SoftLimitMin || desired > a.SoftLimitMax)
{
desired = desired < a.SoftLimitMin ? a.SoftLimitMin : a.SoftLimitMax;
a.SoftLimitLatched = true; // 50 ms; the consumer side raises an alarm and stops the group on that; no IO inside the RT callback
_syncRunning = false;
}
a.CurrentTarget = desired;
output.TargetPosition = desired;
cw = 0x0F;
}
output.ControlWord = cw;
}
Position display converts to degrees with the pulses-per-revolution value read over SDO at connect time:
角度(°) = 脉冲 × 360 / CPR(fall back from0x2604:00to0x608F:01; if neither can be read the CPR is unknown, so raw counts are shown and no angle conversion is done; when0x6091is not 1:1, apply the gear ratio first, then convert to degrees).SoftLimitMin/SoftLimitMaxare read from0x607D:01/0x607D:02at connection time (use the mechanical travel when the drive does not implement soft limits);SoftLimitLatchedis a volatile latch written by the PDO thread, and the alarm text and group stop live in the 50 ms consumer. Alarm / group stop / diagnostics and the UI status refresh (≈50 ms) are separate logic and are not part of the core control.
Why this does not judder or jump
Judder and jumps in multi-axis synchronization are usually not a matter of "the algorithm not being clever enough" but of missing one of the eleven items below:
| Item | Correct practice | If missed |
|---|---|---|
| Start from a 500 µs cycle | 500 µs default, 125–10000 µs recommended (a recommendation, not a product limit); run stable first, then shorten | Starting at 125 µs amplifies jitter and the following error swings |
| DC Sync0 equal to LoopCycle | After LoopCycle = cycleNs passes the read-back check, call slave.ConfigureDC(cycleNs) per axis and check the return value | Frames and the slave cadence fall out of step and the axes drift in phase |
| Issue every axis in the same callback | All axes are written inside one ProcessDataCyclicSync and committed in the same PDO frame | Writing from different threads or instants puts the axes one cycle apart |
| Target = actual when not enabled / handshaking | Not enabled / handshaking / faulted / NotReady always TargetPosition = PositionActualValue | The target still holds the old value at the enable instant and the motor jerks |
| Re-anchor Base during the handshake too | Every cycle in SwitchOnDisabled / ReadyToSwitchOn / SwitchedOn: Base = 实际 − masterPos × Ratio | Enabling while the master axis is advancing makes the target jump by masterPos × Ratio on the cycle OperationEnabled is entered |
| Fault reset through process data | Send one cycle of the reset pulse 0x86 in the PDO callback (bit7 rising edge, bit2 held at 1); return to 0x0006 at all other times | Resetting over SDO upsets the state machine and the drive reports 0x7500 |
| Leave QuickStopActive before enabling | At (sw & 0x6F) == 0x07 send 0x0000 (Disable Voltage) to return to SwitchOnDisabled, then run 0x06→0x07→0x0F on the next cycle | Sending 0x0006 forever: that transition does not exist in this state, so the axis stays stuck and can never be enabled again |
| Check soft limits every cycle | After computing a target, compare it with the 0x607D soft limits (or the mechanical travel); on overrun clamp and raise an alarm + group stop | With a magnified ratio the target runs out of travel and hits the mechanical hard limit |
Never write 0x001F in CSP | Hold 0x000F in CSP and update the target only through 0x607A each cycle | bit4 is the PP/HM NewSetpoint; writing it continuously in CSP makes the drive report a fault |
| Never use Sleep/while as the cycle | Everything hangs off ProcessDataCyclicSync | Indeterminate cycle, large jitter, loss of synchronization with DC |
| Snapshot Base at start | At the instant synchronization starts, Base = 当前实际位置 and the master axis is zeroed | The target jumps to Base + masterPos × Ratio the moment you start |
In one line: steady cycle, same beat, one frame, no target jump, no state confusion. Single-axis commissioning examples (such as the HCFA X3E quarter-turn) cover only part of this and are not a template for multi-axis synchronization.
Operating steps
- Prepare
config.deni: use the Darra EtherCAT master GUI to scan the STF-EC slaves on the bus and export the network configuration asconfig.deni. Put it in theEtherCATRestorefolder under the executable directory (the same file from theSTF-EC_CSP_PPexample can be reused). - Connect: set the cycle in the "Cycle (µs)" field first (500 default, range 125–10000), then click "Connect" and wait for the status to turn green — "Connected (CSP sync axis)" — with all axes listed in the overview table.
- Enable all: click "Enable All"; the drive state of each axis moves to
OperationEnabled. - Set ratios (optional): double-click a row in the "Ratio" column of the overview table and type the value directly, for example
2.000for axis 3 and0.500for axis 4 (matching the example ratios in the system architecture diagram above). All default to1.000. - Start sync: set the "Speed (pulses/s)" value and click "Start Sync". The master axis position begins to advance and the axes move together at their ratios. When every ratio is 1, the axis target positions are identical; with different ratios the positions spread apart in proportion.
- Manual alignment (optional): hold "◀ Master-" / "Master+ ▶" to jog the master axis and watch each axis follow proportionally.
- Stop / emergency stop: "Stop" halts the master axis advance (each axis holds its current position); "Disable All (E-Stop)" performs a controlled stop (Quick Stop
0x0002with the0x6085ramp → confirm QuickStopActive → send0x0000Disable Voltage to return to SwitchOnDisabled, without cutting torque directly) and stops synchronization. Note that0x0006must not be sent from QuickStopActive: Shutdown has bit1/bit2 both at 1 and defines no transition out of QuickStopActive, so the axis would stay stuck permanently;0x0000is used only for this exit and is not a normal stop command. - Disconnect: click "Disconnect" to stop safely and release the master.
Complete example code
The complete runnable project (WinForms UI + config.deni + drive profiles):
The project contains every implementation this page covers: PDO layout discovery and 0x1C12 / 0x1C13 verification, DC Sync0 arming, CiA 402 enable and fault reset, ratio following, soft limits, alarms and group stop. Besides the MOONS' STF-EC, the same project ships two more profiles, HCFA X3E and Ezi-SERVO2; when the drive is changed, the profile is matched automatically by VendorId / ProductId / RevId.
DriveProfiles/DriveProfile/PdoLayout/VerifyPdoAssignmentin the example are helper types inside the project, not SDK public API; the SDK calls (master build, state machine, PDO mapping, SDO, DC, process data callback) are the same as in this page's code.