Multi-axis electronic cams
One virtual master axis drives several slave axes, each following the master phase in real time along a configured cam curve. This is the electronic replacement for mechanical cams in packaging, printing, flying shear and filling machines.
Key points of this example:
- The master axis is a software phase, not a real encoder:
masterPhase ∈ [0,1)acts as the master axis and advances once per PDO cycle (1 ms in the official source for this example). - The slave axes use CSP only (Mode=8): cyclic synchronous position mode, following the cam target position that the master computes cycle by cycle.
The complete source for this example (WinForms + CiA 402 state machine + virtual master axis + cam curve + cyclic CSP following + alarms and diagnostics) is in the GitHub repository: https://github.com/DarraTechnology/Ethercat_Master/tree/main/Windows/CSharp/STF-EC_ECam
Hardware configuration
- Master: Windows 10 × 1 + Intel i5 × 1
- Stepper drives: STF-EC EtherCAT stepper drives × 5 (vendor Shanghai AMP&MOONS' Automation, VendorId
0x00000168, ProductCode0x02) - Protocol: CoE (CiA 402, Profile 402), DC Sync0 1 ms
| Item | Value |
|---|---|
| Vendor | Shanghai AMP&MOONS' Automation |
| VendorId | 0x00000168 |
| Model / ProductCode | STF-EC / 0x02 |
| Axes | the bundled config.deni contains 5 axes (the actual count follows the scan, master.SlaveCount) |
| Control mode | CSP, cyclic synchronous position (Mode = 8) |
| Synchronization | DC Sync0 1 ms (required by CSP) |
Cycle convention: the official source for this example runs at 1 ms (
ConfigureDC(1000000)); the synchronized-axes example defaults to 500 µs. Do not mix the two — when you change the cycle,LoopCycleandConfigureDCmust change together, and the divisor used to advance the phase must be recomputed for the new cycle.
The number of axes is determined by the slaves actually scanned from
config.deni; the UI generates the overview table from that count, so no code changes are needed. All 5 axes can be used as cam slave axes.
Motion parameters and performance figures
- Control cycle: 1 ms (
LoopCycle= DC Sync0, hard-synchronized; the value used by the official source for this example) - Virtual master axis: software phase
masterPhase ∈ [0,1); the master speed is adjustable (RPM) - Cam curves: three types — sine, cycloidal and linear (electronic gear); the stroke (pulses) is adjustable. The curve output range is
[-1, 1], so the stroke is the peak amplitude: full stroke =2 × amp - Phase offset: set independently per axis, so multiple axes can be spread evenly along the cam (for example 5 axes at 0/72/144/216/288°)
- Jump-free engage: on the engage edge the anchor is derived from the current phase,
Base = 实际位置 − Cam(u) × 行程, so following produces no position step - The following-error threshold adapts to the cam speed, so high speed or a large stroke does not cause false alarms
Application scenario
Electronic replacement for mechanical cam mechanisms, typical applications:
- Packaging machines: film feed, cut-off and cross/vertical sealing follow the phase of the master axis (the conveyor chain) with a defined displacement
- Printing presses: each print unit's colour deck registers precisely to the plate roller phase
- Flying shear / rotary cut-off: the knife accelerates and decelerates in sync with the web speed and matches web speed at the instant of the cut
- Filling machines: the filling head rises and falls and opens/closes valves with the carousel phase
How it works
Start with a mechanical cam: the cam profile determines the follower displacement, a function of the master shaft angle, s = f(θ).
An electronic cam turns that profile into a mathematical curve that the controller evaluates and sends out in real time every cycle. This example revolves around four key concepts:
- Advancing the virtual master phase: a software phase
masterPhase ∈ [0,1)replaces a real encoder master shaft and advances once per PDO cycle (1 ms in this example)Δphase = masterRPM / 60 × cycle (s) // 1ms → RPM/60/1000; 500 µs → RPM/60/2000
masterPhase = frac(masterPhase + Δphase) // wraps back to 0 automatically at 1 and loops, one revolution = 0→360°The divisor is not a constant; compute it from
cycleNs(1e9 / cycleNs= cycles per second). If you hard-code/1000, changing the cycle scales the whole master speed — the slave axes still stay synchronized with each other, but the phase no longer matches the configured speed and the cam falls out of step with the external process (conveyor chain / plate roller). - Engage without a jump: a slave axis follows the master only while its "Engaged" checkbox is set. The anchor is not a snapshot of the actual position used as
Base; it is derived asBase = 实际位置 − Cam(当前相位) × 行程, so the target on the engage cycle equals the position the axis is already at, with no position step. TakingBase = 实际位置directly is only valid whenCam(u) = 0(the sine is exactly 0 at u = 0); the cycloidal and linear curves haveCam = −1at u = 0, so the wrong anchor makes the first cycle jump by a full stroke. The same applies to an axis engaged while the cam is running: it must be re-anchored on the engage edge. - Phase offset: each slave axis can have its own phase offset in degrees, so multiple axes are staggered along the cam — for example 5 axes at 0/72/144/216/288°, evenly distributed over one revolution.
- Slave target position formula (every cycle, every engaged axis):
output.TargetPosition = Base + (int)Round( Cam(curve, frac(masterPhase + phaseOffset/360)) × stroke )
Why CSP only (Mode = 8)? An electronic cam requires a new target position to be issued precisely every control cycle, hard-synchronized to the bus cycle — which is exactly the semantics of CSP.
How CSP works here:
- Every cycle the master writes the computed cam target position to
0x607A; the master computes the trajectory, and the drive only follows the position. - DC Sync0 (1 ms) aligns the clocks of all slaves to the same beat, so the cam axes do not drift against each other.
Why not PP? PP (profile position) is point-to-point positioning, and the drive generates the trajectory internally. The master cannot supply a per-cycle cam shape, so PP is unsuitable for cams and this example has no PP branch.
System architecture
The master's job is small: three things per cycle:
- advance the virtual master phase;
- for each engaged slave axis, evaluate the curve at its offset phase and compute the target position;
- maintain the CiA 402 enable handshake and write the target position into the RxPDO.
It performs no internal interpolation and no trajectory planning — the cam shape is entirely determined by the curve function.
Code example
PDO struct definitions
The STF-EC default RxPDO output is 29 bytes and the TxPDO input is 35 bytes. Note that in 0x1A00 the error code comes first and the status word after it; the STF_Input struct is laid out accordingly.
using System.Runtime.InteropServices;
/// <summary>
/// STF-EC stepper drive output PDO (RxPDO 0x1600+0x1601+0x1602+0x1603, 29 bytes total)
/// The electronic cam uses only ControlWord / ModesOfOperation / TargetPosition,
/// The remaining fields are kept to match the complete PDO assignment of config.deni (the size must line up exactly).
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct STF_Output // 29 bytes
{
// 0x1600 - the three entries the cam follow actually uses
public ushort ControlWord; // 0x6040:0 control word (CiA402 state machine)
public sbyte ModesOfOperation; // 0x6060:0 mode of operation (CSP = 8)
public int TargetPosition; // 0x607A:0 target position (pulses, computed by the cam every cycle)
// 0x1601 - reserved (CSP does not use it, but it is in the PDO assignment and must be kept as a placeholder)
public uint ProfileVelocity; // 0x6081:0
public uint ProfileAcceleration; // 0x6083:0
public uint ProfileDeceleration; // 0x6084:0
// 0x1602
public int TargetVelocity; // 0x60FF:0
// 0x1603
public uint PhysicalOutputs; // 0x60FE:1 digital outputs
public ushort TouchProbeFunction; // 0x60B8:0
}
/// <summary>
/// STF-EC stepper drive input PDO (TxPDO 0x1A00+0x1A01+0x1A02+0x1A03, 35 bytes total)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct STF_Input // 35 bytes
{
// 0x1A00 (note: on the STF-EC this PDO puts the error code first and the status word second)
public ushort ErrorCode; // 0x603F:0 error code (!= 0 means a drive fault)
public ushort StatusWord; // 0x6041:0 status word (used to read the CiA402 state machine)
public sbyte ModesOfOperationDisplay; // 0x6061:0
// 0x1A01
public int PositionActualValue; // 0x6064:0 actual position (pulses; used to back out Base = actual - Cam(u) x travel)
// 0x1A02
public int VelocityActualValue; // 0x606C:0 actual velocity
// 0x1A03
public uint DigitalInputs; // 0x60FD:0
public ushort TouchProbeStatus; // 0x60B9:0
public int TouchProbe1PosValue; // 0x60BA:0
public int TouchProbe1NegValue; // 0x60BB:0
public int TouchProbe2PosValue; // 0x60BC:0
public int TouchProbe2NegValue; // 0x60BD:0
}
Connecting and DC synchronization
The connection sequence is Build → 设定周期 → PreOp → (逐轴 PDO 分配重写 + 回读校验 + DC) → SafeOp → (尺寸自检 + PDO 初值) → OP.
Two prerequisites for CSP cams:
- The authoritative PDO layout is the ESI default mapping. The STF-EC default assignment is 4+4 (29 bytes out / 35 bytes in); the official example below writes that same 4+4 in PreOp in one go. This is safe only if the assignment entries match the ESI default exactly. When you change to another model, read
0x1C12/0x1C13and check them against the ESI; do not rewrite the assignment entries from guesswork — one wrong entry misconfigures the slave. For a safer read-only verification, see the connection section of Synchronized axes / electronic gearing. - The cycle and DC Sync0 use the same value:
LoopCycleandConfigureDCtake the samecycleNs(1 ms in this example); otherwise PDO frames lose sync with the slave beat and the axis clocks drift.
Only the key steps are shown below; boilerplate such as try/catch and cancellation checks is omitted.
// Build the master and scan the slaves (EnableAutoStartup runs the startup commands automatically)
var buildResult = new DarraEtherCAT()
.SetENI(deniPath) // Load config.deni (real topology with SHA256 verification)
.EnableAutoStartup()
.Build();
if (!buildResult.Success) { /* Initialisation failure handling*/ return; }
var master = buildResult.Master!; // When Success = true, Master is never null
int slaveCount = master.SlaveCount; // The axis count is decided by the actual scan
// Cycle time: set LoopCycle and read it back to verify before any state transition (readback != requested -> refuse to enter the motion chain)
uint cycleNs = 1000000; // The official source of this case uses 1 ms; the synchronised axis case defaults to 500 µs; do not mix the two
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
// SDO writes that change the PDO assignment are only possible after entering PreOp
// 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 / DC"); // Failed to enter PreOp — refusing to continue configuring PDO / DC
for (int i = 0; i < slaveCount; i++)
{
var slave = master.Slaves[i];
// ① Official example: in PreOp write the PDO assignment as the STF-EC 4+4 (29 out / 35 in).
// This code is safe only when it is "exactly the ESI default mapping"; for another model you must check against the ESI first,
// Never rewrite 0x1C12/0x1C13 on a guess - one wrong assignment entry breaks the slave configuration and it will not reach OP afterwards.
// This is a one-off initialisation (written in PreOp, SM2 not active yet), not part of the control loop.
// CoE may be null (no mailbox / protocol not recognised); dereferencing it directly throws an NRE - guard first
if (slave.CoE == null)
throw new Exception($"轴{i + 1} 无 CoE 协议实例 — 无法重写 0x1C12/0x1C13 PDO 分配"); // Axis{i + 1} has no CoE protocol instance — the 0x1C12/0x1C13 PDO assignment cannot be rewritten
slave.CoE.SDOWrite(0x1C12, 0, new byte[] { 0 }); // Clear the RxPDO assignment count first
slave.CoE.SDOWrite(0x1C12, 1, BitConverter.GetBytes((ushort)0x1600));
slave.CoE.SDOWrite(0x1C12, 2, BitConverter.GetBytes((ushort)0x1601));
slave.CoE.SDOWrite(0x1C12, 3, BitConverter.GetBytes((ushort)0x1602));
slave.CoE.SDOWrite(0x1C12, 4, BitConverter.GetBytes((ushort)0x1603));
slave.CoE.SDOWrite(0x1C12, 0, new byte[] { 4 }); // Write back an assignment of 4 RxPDOs
slave.CoE.SDOWrite(0x1C13, 0, new byte[] { 0 }); // Clear the TxPDO assignment
slave.CoE.SDOWrite(0x1C13, 1, BitConverter.GetBytes((ushort)0x1A00));
slave.CoE.SDOWrite(0x1C13, 2, BitConverter.GetBytes((ushort)0x1A01));
slave.CoE.SDOWrite(0x1C13, 3, BitConverter.GetBytes((ushort)0x1A02));
slave.CoE.SDOWrite(0x1C13, 4, BitConverter.GetBytes((ushort)0x1A03));
slave.CoE.SDOWrite(0x1C13, 0, new byte[] { 4 }); // Write back an assignment of 4 TxPDOs
// ② Enable DC Sync0 = the same cycleNs (1 ms in this case) to align every slave clock to the same tick - required for the CSP cam
// SYNC0 and LoopCycle must be equal, otherwise the PDO frames and the slave tick drift apart
if (slave.HasDC) slave.ConfigureDC(cycleNs); // Sync0 = 1ms
// 0x10F1:02 = sync error counter limit, used to relax the tolerance; a write failure is only logged and is not a motion fault (some drives have no such object)
slave.CoE?.SDOWrite(0x10F1, 2, BitConverter.GetBytes((ushort)65535));
}
// ②' Read the assignment count back: check the return value of all 12 SDOWrite calls above, but the final criterion is the read-back value -
// On a failed write, or when the drive accepts only some entries, this must catch it - otherwise the PDO size self-check reports "size mismatch" instead of the real cause
for (int i = 0; i < slaveCount; i++)
{
var rx = master.Slaves[i].CoE?.SDORead(0x1C12, 0);
var tx = master.Slaves[i].CoE?.SDORead(0x1C13, 0);
if (rx == null || rx.Length < 1 || rx[0] != 4 ||
tx == null || tx.Length < 1 || tx[0] != 4)
throw new Exception($"轴{i + 1} PDO 分配回读不是 4+4 (0x1C12:00={rx?[0]}, 0x1C13:00={tx?[0]}) — 拒绝进 OP"); // Axis{i + 1} PDO assignment read-back is not 4+4 (0x1C12:00={rx?[0]}, 0x1C13:00={tx?[0]}) — refusing to enter OP
}
if (!master.SetState(EcState.SafeOp))
throw new Exception("进入 SafeOp 失败 — 拒绝进 OP"); // Failed to enter SafeOp — refusing to enter OP
// ③ PDO size self-check: compare the struct against the actual process image byte count of the drive and fail immediately on a mismatch
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)
{ /* The drive's current PDO mapping != config.deni, report an error*/ return; }
}
// ④ Before entering OP: align the target position with the current actual position so nothing jumps at power-on
// Use 0x0006 for the control word (the real stop command); bit4 (0x0010) is undefined in CSP, so never write 0x001F -
// Measured on the HCFA X3E: writing 0x001F repeatedly in CSP makes the drive report 0x7500 (a CiA communication-class error).
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.ModesOfOperation = 8; // CSP
output.TargetPosition = input.PositionActualValue; // Target = current actual, no motion
}
if (!master.SetState(EcState.OP)) // Enter OP, the PDO control thread takes over; if this fails nothing moved, so it must not count as success
throw new Exception("进入 OP 失败 — 运动链路未建立"); // Failed to enter OP — the motion link is not established
Cam curve function Cam()
Cam(type, u) takes the master phase u ∈ [0,1) and returns a normalized displacement [-1,1]; multiplying it by the stroke in pulses gives the actual position offset. The three curves correspond to three typical mechanical cam profiles:
// Take the fractional part: fold any phase into one turn of [0,1)
static double Frac(double x) => x - Math.Floor(x);
/// <summary>
/// Cam curve: u in [0,1) is the master phase, returns normalised displacement in [-1,1].
/// </summary>
public static double Cam(int type, double u)
{
u = Frac(u); // Fold the phase into [0,1)
switch (type)
{
case 0: // Sine: one complete sine round trip per turn, smooth acceleration, the most common choice
return Math.Sin(2.0 * Math.PI * u);
case 1: // Cycloid: start/stop acceleration is continuous (no jerk), the first choice for high-speed cams
{
double rise;
if (u < 0.5)
{
double s = u * 2.0; // s ∈ [0,1)
rise = s - Math.Sin(2.0 * Math.PI * s) / (2.0 * Math.PI); // Smooth ramp 0->1
}
else
{
double s = (u - 0.5) * 2.0; // s ∈ [0,1)
double up = s - Math.Sin(2.0 * Math.PI * s) / (2.0 * Math.PI);
rise = 1.0 - up; // Mirror falls back 1->0
}
return rise * 2.0 - 1.0; // 0..1 mapped to -1..1
}
case 2: // Linear / electronic gear: linear ramp, displacement strictly proportional to the master phase
return u * 2.0 - 1.0;
default:
return 0.0;
}
}
Key insight: a synchronized axis (electronic gear) is the linear special case of a cam curve.
With
type = 2(linear), the slave displacement2u-1is strictly proportional to the master phase, which is exactly the 1:1 ratio following of an electronic gear / synchronized axis.In other words, "electronic gear" is just the simplest straight line in the cam curve family. The two share one origin: a cam is the general
s = f(θ), and a gear is the case wherefis linear.
Cyclic CSP following control
The cam control runs on the SDK's cyclic PDO callback and executes once per bus cycle (1 ms in the official source for this example), doing three things:
- on cam start, set the re-anchor flag (the actual anchoring is done in
StepCam, which derivesBasefrom the current phase); - advance the virtual master phase;
- call
StepCamfor each axis, which runs the CiA 402 handshake and computes the cam target position.
There is also alarm detection and following-error evaluation: the PDO hot path only sets volatile latches, and the actual decisions and presentation live on the 50 ms UI consumer side. That part is omitted here.
Real-time control must hang off the SDK's cyclic PDO callback (
ProcessDataCyclicSync), driven hard-synchronized by the bus cycle (DC Sync0 =cycleNs, 1 ms in this example). Never spin withThread.Sleep— the cycle then becomes indeterminate, jitter is large and it loses DC synchronization, which is not deterministic real-time control.
// The cycle set at connect time (ns), the same value as LoopCycle / DC Sync0; phase advance and following error conversion both derive from it
uint _cycleNs = 1_000_000;
// Real-time control is attached to the SDK's PDO cycle callback - hard-synchronised by the bus cycle (1 ms),
// Runs per cycle in the SDK's PDO thread context. Never use Thread.Sleep / a while spin.
master.Events.ProcessDataCyclicSync += OnPdoCycle;
// PDO cycle callback: the SDK calls it automatically once per bus cycle (LoopCycle = 1 ms),
// Advance the master phase + per-axis cam following. Parameter mi = master index.
void OnPdoCycle(ushort mi)
{
var m = master;
if (m == null) return;
var arr = axes;
_pdoCycle++;
int curve = _curveType;
int amp = _amplitude; // Travel (pulses): the curve outputs +/-1, so the actual displacement = +/-amp
// ① Cam start / phase-zero latch: zero the phase (if requested) + force a re-anchor of Base on all axes this tick.
// The anchor is back-calculated by StepCam from the **current phase**: Base = actual - Cam(u) x travel; it cannot simply be Base = actual:
// Only a sine curve with Cam(0) = 0 happens to be equivalent; cycloid and linear have Cam = -1 at u=0,
// Taking the actual position straight as Base makes the very first tick jump the target to "actual - travel".
if (_camStartLatch)
{
// Zeroing the phase must come first, otherwise you anchor to the pre-zero phase
if (Interlocked.Exchange(ref _masterPhaseResetFlag, 0) == 1)
_masterPhase = 0.0;
for (int i = 0; i < arr.Length; i++)
arr[i].EngagedPrev = false; // Force a re-anchor (even following axes must re-anchor, otherwise zeroing the phase is a position step)
_camStartLatch = false;
}
// ② Advance the master phase: delta phase = rpm/60 × cycle (seconds); the divisor is computed from cycleNs instead of hard-coding 1000
if (_camRunning)
_masterPhase = Frac(_masterPhase + _masterRpm / 60.0 * (_cycleNs / 1_000_000_000.0));
double phase = _masterPhase;
// ③ Per-axis CSP following - write each axis target position consecutively inside the same callback and commit them 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>();
StepCam(a, in input, ref output, curve, amp, phase);
// Following error: judged only when "this tick really is following" (engaged + cam running + OperationEnabled); the criterion = actual - the target sent this tick.
// The threshold scales with this tick's target increment: in CSP the actual position naturally lags the target by about one cycle increment, so a fixed threshold always false-alarms at high speed / large travel.
int fe = input.PositionActualValue - output.TargetPosition;
int cmdDelta = output.TargetPosition - a.PrevTarget;
a.PrevTarget = output.TargetPosition;
bool following = a.Engaged && _camRunning && IsOperationEnabled(input.StatusWord);
if (following && Math.Abs(fe) > a.FollowErrLimit + 4 * Math.Abs(cmdDelta))
{
a.FollowErrLatched = true; // 50 ms; the consumer side raises an alarm and stops the group on that; no IO inside the RT callback
_camRunning = false; // All followers stop together at the current phase
}
else if (!following) a.FollowErrLatched = false;
}
}
// Single-axis CSP cam following: maintain the CiA402 enable handshake (0x06->0x07->0x0F); when OperationEnabled, engaged and the cam is running, send targets from the curve.
// Default output = stop command 0x0006 + target = the current actual position; QuickStopActive is the one state where 0x0000 must be sent.
void StepCam(AxisController a, in STF_Input input, ref STF_Output output,
int curve, int amp, double phase)
{
output.ModesOfOperation = 8; // 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 the moment enable returns.
a.CurrentTarget = actPos;
output.TargetPosition = actPos;
if (a.FaultReset) // Fault reset: 0x86 = bit7 rising edge (bit2 held at 1)
{
cw = 0x86;
a.FaultReset = false; // Automatically back to 0x0006 on the next tick
}
else if (IsFault(sw)) // Fault state: wait for [fault reset], the target holds the actual position
{
}
else if (!a.ServoEnabled) // Disabled: target = actual
{
}
else if ((sw & 0x4F) == 0x00) // NotReadyToSwitchOn: wait, target = actual
{
}
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 ((sw & 0x6F) == 0x07) // QuickStopActive: only Disable Voltage can exit
{
// From QuickStopActive there is only bit1=0 (Disable Voltage, 0x0000) or bit2=0 (Quick Stop)
// it can return to SwitchOnDisabled; Shutdown 0x0006 has bit1=bit2=1 which is undefined for that state, so sending it forever wedges.
cw = 0x0000;
}
else if (IsOperationEnabled(sw))
{
cw = 0x0F; // Stay enabled
if (a.Engaged && _camRunning)
{
// ★ Core: follower target = Base + Cam(curve, master phase + that axis' phase offset) × travel
double u = Frac(phase + a.PhaseOffsetDeg / 360.0); // Add a phase offset to stagger the axes
int camNow = (int)Math.Round(Cam(curve, u) * amp);
// Re-anchor points: (a) start / phase-zero latch (forcing EngagedPrev=false); (b) the engage edge; (c) the first tick after enabling.
// Back-calculation makes "this tick's target == actual", the same semantics as the start latch; without a re-anchor it would jump to camNow in one step.
if (!a.EngagedPrev) a.Base = actPos - camNow;
a.CurrentTarget = a.Base + camNow;
output.TargetPosition = a.CurrentTarget;
}
// Not engaged / cam not running: hold the current actual position (written back earlier)
}
// Record "anchored" only when this tick really is following: not enabled / not engaged does not count as anchored, so the first tick after enabling re-anchors
a.EngagedPrev = a.Engaged && _camRunning && IsOperationEnabled(sw);
output.ControlWord = cw;
}
CiA 402 state machine checks are all mask comparisons on the status word
sw:
- Running states use
0x6F:IsSwitchOnDisabled=(sw & 0x6F) == 0x40,IsReadyToSwitchOn=0x21,IsSwitchedOn=0x23,IsOperationEnabled=0x27- Fault / not ready use
0x4F:IsFault=(sw & 0x4F) == 0x08,NotReadyToSwitchOn=(sw & 0x4F) == 0x00Do not use
0x4Ffor running-state checks — the bit4/bit5 difference is misread as "not in a running state", so the handshake stalls or the drive is repeatedly disabled.The enable handshake sends the control words
0x06 → 0x07 → 0x0Fin order; a fault reset sends one cycle of0x86, and at all other times the control word is0x0006. Never write0x001Fin CSP (bit4 is the PP/HM NewSetpoint and is undefined in CSP).Some drives (for example the HCFA X3E) require a clean rising edge with bit2 = 1: alternate
0x0006↔0x0086over two cycles to do the reset (bit2 is 1 in both). The only case where0x0000must be written is leaving QuickStopActive ((sw & 0x6F) == 0x07) — that state has only two exits, Disable Voltage and Quick Stop, and0x0006has no defined transition from it; apart from that, never use0x0000as a stop command (bit2 is active low and holds QuickStop, and the drive then reports0x7500in CSP).
AxisControllerfields used by the callback:Engaged/PhaseOffsetDeg/ServoEnabled/FaultResetare written by the UI thread;Base/EngagedPrev/PrevTarget/FollowErrLatchedare written only by the PDO thread;FollowErrLimitis set at connection time from the stroke and the drive's following bandwidth.Position units:
0x607A/0x6064both use the drive position unit (encoder resolution0x608Fconverted through the0x6091gear ratio and the0x6092feed constant). "Pulses" on this page means that position unit — the strokeamp, the following-error threshold and the pulses-per-revolution (CPR) conversion must all be in the same unit; when0x6091is not 1:1, fold the gear ratio in first, otherwise the stroke and the threshold are off by the same factor.
Operating steps
- Connect: run Init → PreOp → SafeOp → OP, setting
LoopCycleand DC Sync0 to the same cycle, checking the PDO assignment against the ESI and running the size self-check before entering CSP. - Enable all axes: each axis runs the CiA 402 handshake (
0x06 → 0x07 → 0x0F) into OperationEnabled. - Select curve and stroke: choose the cam curve (sine / cycloidal / linear) and the stroke in pulses; the UI previews the curve shape immediately.
- (Optional) Set phase offsets: give each axis a different angle so the axes are spread evenly along the cam (for example 0/72/144/216/288°).
- Engage all axes: engage the slave axes on the cam — the engage edge uses the derived anchor
Base = 实际 − Cam(u) × 行程, so following starts without a jump. - Start the cam: set the master RPM and start; the master phase begins to advance and the engaged axes follow the curve. Stopping leaves each axis at its current position. Zeroing the phase must happen in the same cycle as re-anchoring
Base(zero the phase first, then deriveBasefrom the new phase); setting onlymasterPhaseto 0 without re-anchoring makes the target jump fromBase + Cam(旧相位) × 行程toBase + Cam(0) × 行程— with the cycloidal or linear curve that is a position step of a full stroke.
After connecting or powering up, the system does not move on its own — the target position is initialized to the current actual position. The motor moves only after you enable → engage → start the cam.
There are also several diagnostic behaviours:
- alarm severity levels (fault / warning / information);
- group-stop interlock on a fault;
- false-alarm suppression for following error (a grace window).
Complete example code
The complete runnable project for this example (WinForms + CiA 402 state machine + virtual master axis + cam curve + CSP following + alarms and diagnostics):
- STF-EC_ECam — the electronic cam example described on this page.
- STF-EC_SyncAxis — synchronized axes / electronic gearing (the linear special case of a cam with the linear curve); see that example for the read-only PDO assignment check.
- STF-EC_CSP_PP — CSP / PP jog positioning on the same drive model, for comparing the two modes.