Skip to main content

HCFA X3E · 500 µs CSP

A single-axis CiA 402 CSP use case. One HCFA X3E drive, bus cycle 500 µs (2000 Hz). The master writes the target position 0x607A every cycle.

Single-axis commissioning example

This page is a single-axis CSP commissioning example, not a synchronized-axis or electronic-gearing use case: it verifies cyclic synchronous position control on one drive only. For strict multi-axis coupling (virtual master axis, gear-ratio following), see Synchronized axes / electronic gearing.

Project: HCFA_X3E_QuarterTurn (a sample project in this repository).

What it does​

The interface has three buttons: Connect → Enable → Start.

After Start, the motor turns on a fixed cadence: 250 ms for 1/4 turn, a 100 ms dwell, then the next turn (the PdoQuarterStep profile of QTR250D100). 500 µs must be written in every 0x607A cycle, including during the dwell, to hold the end position. Do not compress the 1/4 turn to the 100 ms profile: on a measured HCFA X3E the following response becomes too steep and the drive reports 0x7500 after 2–3 steps; the same measurement shows the shorter 20 ms profile dropping enable as well.

ItemValue
DriveHCFA X3E
Cycle500 µs
ModeCSP (0x6060 = 8)
Axes1
ConfigurationThe .deni exported by the master tool, placed in the program directory

Enable sequence: advance 0x6040 through 06 → 07 → 0F. The step is driven by the status word 0x6041 and issued from the PDO cyclic callback; do not guess the state with fixed delays.

Stop semantics: first write the current cycle's actual position to 0x607A, and disable only after the axis has come to rest. For a loaded or vertical axis, send 0x0006 (Shutdown) to remove enable smoothly; the Stop button in this sample's GUI sends 0x0000 (Disable Voltage, which removes torque immediately) after the axis has settled. Do not write 0x0000 on handshake cycles or idle cycles in CSP (a measured HCFA X3E latches 0x7500); send 0x0006 while idle. 0x0000 is only for leaving QuickStopActive and for power-off after the axis has settled.

Emergency stop: the software side can send 0x0002 (Quick Stop); the deceleration profile is selected by 0x605A — with 0x605A = 2 the drive decelerates at the quick-stop deceleration set in 0x6085. A software Quick Stop does not replace a hardwired emergency stop or STO. Once the status word shows QuickStopActive ((sw & 0x6F) == 0x07), you must first send 0x0000 (Disable Voltage) to return to SwitchOnDisabled, then run the handshake again with 0x0006 → 0x0007 → 0x000F; 0x0006 has no defined transition in that state, and the axis stays stuck in QuickStopActive.

CSP interpolation: 0x60C2 must have the same value as LoopCycle (500 µs = 50 × 10⁻⁵ s, that is 0x60C2:01 = 50, :02 = -5). Write this object over SDO after the SafeOp mapping is complete and read it back; a write in PreOp is discarded by the SM reconfiguration. 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.

Measured on a HCFA X3E: in CSP, hold 0x6040 at 0x000F; bit4 of 0x001F is the NewSetpoint bit for PP/HM and is undefined in CSP — writing it continuously makes the drive report 0x7500 (CiA communication class) while moving.

PDO​

  • Outputs 9 bytes (RxPDO 0x1600): 6040(2), 6060(1), 607A(4), 60B8(2)
  • Inputs 25 bytes (TxPDO 0x1A00): 603F(2), 6041(2), 6064(4), 6061(1), 60B9(2), 60BA(4), 60F4(4), 60FD(4), 213F(2)

The value in parentheses is the byte size of each object; add them byte by byte in ESI entry order: 2+1+4+2 = 9, 2+2+4+1+2+4+4+4+2 = 25.

The struct field order must match that order exactly. With Pack = 1 there must be no implicit padding; one wrong field shifts everything after it.

The process image is mapped onto the structs. Changing a field is changing the PDO.

Cyclic callback​

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using DarraEtherCAT_Master;
using HCFA_X3E_QuarterTurn; // PdoQuarterStep lives in the sample project (internal); change the namespace when you copy it into your own project

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct X3eIn
{
public ushort ErrorCode; // 0x603F 2 B
public ushort StatusWord; // 0x6041 2 B
public int ActualPosition; // 0x6064 4 B
public sbyte ModeDisplay; // 0x6061 1 B
public ushort ProbeStatus; // 0x60B9 2 B
public int ProbePos1; // 0x60BA 4 B
public int FollowingError; // 0x60F4 4 B
public uint DigitalInputs; // 0x60FD 4 B
public ushort ServoError; // 0x213F 2 B (ESI: Servo Error)
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct X3eOut
{
public ushort ControlWord; // 0x6040 2 B
public sbyte Mode; // 0x6060 1 B
public int TargetPosition; // 0x607A 4 B
public ushort ProbeFunction; // 0x60B8 2 B
}

const uint CYCLE_NS = 500_000; // 500 µs

var build = new DarraEtherCAT()
.SetENI("config.deni")
.EnableAutoStartup()
.Build();
if (!build.Success) throw new InvalidOperationException(build.Message);
var master = build.Master!;
if (master.SlaveCount < 1) throw new InvalidOperationException("DENI 中没有从站"); // No slaves in the DENI

// Set the cycle first and read it back; refuse to enter the motion path if it does not match
master.LoopCycle = CYCLE_NS;
if (master.LoopCycle != CYCLE_NS)
throw new InvalidOperationException($"LoopCycle 读回 {master.LoopCycle}ns ≠ {CYCLE_NS}ns"); // LoopCycle read back {master.LoopCycle}ns ≠ {CYCLE_NS}ns

if (!master.SetState(EcState.PreOp)) throw new InvalidOperationException("PreOp 失败"); // PreOp failed

// DC Sync0 must equal the bus cycle. Check both capabilities: HasDC (the ESC hardware bit) and HasEsiDcSync (whether the ESI declares DC-Sync0):
// with HasDC alone you would force ESC onto a slave whose ESI reports capable but whose SYNC0 does not declare it; that slave refuses to enter OP and returns no error code.
// The sample GUI's DENI defaults to FreeRun (active_dc=0) and does not arm SYNC0; only the HIL acceptance path arms it explicitly with ConfigureDC
// When DC is needed, align DENI / DistributedClocks / CycleTime0 in the Sync0CycleNs with LoopCycle as well.
var dcSlave = master.Slaves[0];
if (dcSlave.HasDC && dcSlave.HasEsiDcSync)
{
if (!dcSlave.ConfigureDC(CYCLE_NS))
throw new InvalidOperationException("DC Sync0 配置失败 — CSP 依赖周期同步"); // DC Sync0 configuration failed — CSP depends on cyclic synchronization
}
else
{
Console.WriteLine("警告: 从站无 DC 硬件或 ESI 未声明 DC-Sync0, 未配置 Sync0 (CSP 退化为 SM 事件同步, 精度下降)"); // Warning: the slave has no DC hardware or the ESI does not declare DC-Sync0, so Sync0 was not configured (CSP degrades to SM event synchronization, accuracy reduced)
}

if (!master.SetState(EcState.SafeOp)) throw new InvalidOperationException("SafeOp 失败"); // SafeOp failed

// The CSP interpolation cycle 0x60C2 must equal LoopCycle 500 µs = 50 × 10^-5 s.
// Write it after SafeOp (PDO mapping complete); a write in PreOp is discarded by the SM reconfiguration.
const sbyte INTERP_VALUE = 50;
const sbyte INTERP_INDEX = -5;
var coe = master.Slaves[0].CoE ?? throw new InvalidOperationException("从站不支持 CoE, 无法写 0x60C2"); // The slave does not support CoE, 0x60C2 cannot be written
if (!coe.SDOWrite(0x60C2, 0x01, new byte[] { (byte)INTERP_VALUE }, out var interpWrite) || !interpWrite.Ok)
throw new InvalidOperationException($"0x60C2:01 写入失败: {interpWrite}"); // 0x60C2:01 write failed: {interpWrite}
if (!coe.SDOWrite(0x60C2, 0x02, new byte[] { unchecked((byte)INTERP_INDEX) }, out interpWrite) || !interpWrite.Ok)
throw new InvalidOperationException($"0x60C2:02 写入失败: {interpWrite}"); // 0x60C2:02 write failed: {interpWrite}
byte[] interpRead = coe.SDORead(0x60C2, 0x01, out var interpReadResult);
if (!interpReadResult.Ok || interpRead == null || interpRead.Length < 1 ||
interpRead[0] != (byte)INTERP_VALUE)
throw new InvalidOperationException("0x60C2:01 读回不一致"); // 0x60C2:01 read-back mismatch

// Before entering OP target = actual, mode CSP, control word Shutdown (never 0x0000)
{
ref readonly var input = ref master.Slaves[0].PDO.InputsMapping<X3eIn>();
ref var output = ref master.Slaves[0].PDO.OutputsMapping<X3eOut>();
output.Mode = 8;
output.ControlWord = 0x0006;
output.TargetPosition = input.ActualPosition;
}

if (!master.SetState(EcState.OP)) throw new InvalidOperationException("OP 失败"); // OP failed

// After entering OP, check the working counter: actual must equal a non-zero expected exactly; do not enable if any slave is dropping frames.
// The first one or two cycles after entering OP can be transient; wait for a bounded 2 s and do not take "connected" for "the bus is good".
{
var wkcDeadline = DateTime.UtcNow.AddSeconds(2);
while (master.Diagnostics.ExpectedWKC == 0 ||
master.Diagnostics.WKC != master.Diagnostics.ExpectedWKC)
{
if (DateTime.UtcNow > wkcDeadline)
throw new InvalidOperationException(
$"WKC 不一致: actual={master.Diagnostics.WKC} expected={master.Diagnostics.ExpectedWKC}"); // WKC mismatch: actual={master.Diagnostics.WKC} expected={master.Diagnostics.ExpectedWKC}
System.Threading.Thread.Sleep(10);
}
}

// The UI thread only sets requests; the enable handshake is advanced by the PDO callback from the status word
// (in a real project put these three in class fields and mark them volatile; this is a single-file snippet)
bool enableRequested = false;
bool faultResetRequested = false;
int faultResetTicks = 0;

// The enabling button only sets a request and never writes 0x6040; the Fault reset button only sets a request, and the callback emits the bit7 rising edge
// btnEnable.Click += (_, __) => enableRequested = true;
// btnFaultReset.Click += (_, __) => faultResetRequested = true;

var quarterStepper = new PdoQuarterStep.Stepper(); // official incremental trajectory: one step per cycle plus a step guard
int origin = 0; // actual position anchored on first entry into OperationEnabled
int ppr = 131072; // pulses per revolution (default; take the real value from the encoder resolution read over SDO at 0x608F, do not estimate)
if (ppr <= 0 || ppr % 4 != 0)
throw new InvalidOperationException($"PPR 必须 > 0 且可被 4 整除, 当前 {ppr}"); // PPR must be > 0 and divisible by 4, currently {ppr}
int quarter = ppr / 4; // target increment for 1/4 turn (pulses)
bool wasEnabled = false;

master.Events.ProcessDataCyclicSync += _ =>
{
ref readonly var input = ref master.Slaves[0].PDO.InputsMapping<X3eIn>();
ref var output = ref master.Slaves[0].PDO.OutputsMapping<X3eOut>();

ushort sw = input.StatusWord;
bool opEnabled = (sw & 0x6F) == 0x27; // the running state uses 0x6F (0x4F would mask 0x27 into 0x07)
bool fault = (sw & 0x4F) == 0x08; // the fault state uses 0x4F

output.Mode = 8; // 0x6060 = 8 (CSP)

// 1. Fault reset: bit7 must be a single rising edge. Low phase 0x0006, high phase 0x0086;
// never write 0x0000 (Disable Voltage) or 0x0080 (bit2 is active low and holds QuickStop).
if (faultResetRequested && fault)
{
faultResetTicks++;
output.ControlWord = ((faultResetTicks / 400) % 2 == 0) ? (ushort)0x0086 : (ushort)0x0006;
output.TargetPosition = input.ActualPosition;
wasEnabled = false;
return;
}
faultResetRequested = false;
faultResetTicks = 0;

// 2. Not enabled / fault / handshake in progress / QuickStop / NotReady: target = actual
if (!enableRequested || fault || !opEnabled)
{
output.ControlWord = NextEnableCommand(sw, enableRequested && !fault);
output.TargetPosition = input.ActualPosition;
wasEnabled = false; // re-anchor origin when enabling again; do not chase the old trajectory
return;
}

// 3. Compute and issue the target only in OperationEnabled
output.ControlWord = 0x000F; // CSP holds 0x000F; 0x001F of bit4 is the PP/HM NewSetpoint

// First entry into OperationEnabled: take the current actual position as origin and reset the trajectory state.
// The official Next anchors on the first cycle without advancing; after that each cycle advances one increment with a step guard, and missed cycles are not made up from the wall clock.
if (!wasEnabled)
{
origin = input.ActualPosition;
quarterStepper = default;
wasEnabled = true;
}

bool inMove;
long which;
int target = PdoQuarterStep.Next(
ref quarterStepper, origin, quarter,
Stopwatch.GetTimestamp(), Stopwatch.Frequency,
out inMove, out which);
output.TargetPosition = target;
};

/// <summary>
/// Advance the CiA 402 enable sequence from the status word: 0x06 → 0x07 → 0x0F
/// </summary>
static ushort NextEnableCommand(ushort sw, bool enable)
{
if ((sw & 0x6F) == 0x07) return 0x0000; // QuickStopActive: the only exit is Disable Voltage
if (!enable) return 0x0006; // Shutdown
if ((sw & 0x4F) == 0x40) return 0x0006; // SwitchOnDisabled
if ((sw & 0x6F) == 0x21) return 0x0007; // ReadyToSwitchOn
if ((sw & 0x6F) == 0x23) return 0x000F; // SwitchedOn
if ((sw & 0x6F) == 0x27) return 0x000F; // OperationEnabled
return 0x0006; // NotReady / FaultReaction
}

PdoQuarterStep.Stepper / Next are in PdoQuarterStep.cs in the sample project in this repository: one step per cycle, the first cycle anchors the origin, missed cycles are not made up from the wall clock, and there is a step guard on 0x607A. ppr must be greater than 0 and divisible by 4; take the real value from 0x608F read over SDO, not from an estimate.

Complete example code​

The code on this page is the core of the sample project; the complete runnable project (WinForms UI + PdoQuarterStep.cs + a site config.deni):

https://github.com/DarraTechnology/Ethercat_Master/tree/main/Windows/CSharp/HCFA_X3E_QuarterTurn

The cyclic path inside the project uses CopyInputPdo / WriteOutputPdo to take a whole-frame snapshot and write it back (decode or confirm the write only after Success and the 25 B / 9 B size alignment); this page tells the same story with the struct mapping of InputsMapping / OutputsMapping. Both forms address the same process image.