Skip to main content

3-axis gantry robot

Multi-axis synchronization example

This page is a multi-axis synchronization example: the three axes are driven by the same PDO cyclic callback and interpolated on the same time base. For single-axis jogging or single-axis CSP commissioning, see Single-axis CSP example.

Hardware configuration​

  • Master: Windows 10 × 1 + Intel i5 × 1
  • Coupler: EK1100 coupler × 1 + EL2008 digital output × 1 + EL1008 digital input × 1
  • Motion control: Panasonic MDDLT54BF servo drives × 3 + servo motors × 3
  • End effector: SMC MHZ2-16D pneumatic parallel gripper × 1
  • Topology order (slave index starting at 0, 6 slaves in total): EK1100 → X-axis servo → Y-axis servo → Z-axis servo → EL2008 → EL1008

Cost breakdown​

CategoryModel / specificationReference unit price (¥)QuantitySubtotal (¥)
CouplerEK11008001800
Digital outputEL20084001400
Digital inputEL10083501350
Servo drivePanasonic MDDLT54BF2,00036,000
Servo motor400W servo motor80032,400
Pneumatic gripperSMC MHZ2-16D5001500
Industrial PCIntel i5 class3,00013,000
Total for the line (reference)≈ ¥13,450

These are reference prices (RMB) for the core components; mechanical structure, cabling and air supply are not included.

Performance figures​

  • Positioning accuracy: ±0.05 mm
  • Maximum speed: X/Y axes 2 m/s, Z axis 1 m/s
  • Repeatability: ±0.02 mm

Application scenario​

Injection molding machine take-out gantry.
Panasonic MDDLT54BF servos drive the X/Y/Z axes; the pneumatic gripper picks up the molded or machined part and places it on a tray, and trapezoidal velocity profile interpolation keeps the motion smooth.

Data acquisition

This setup is often paired with a data acquisition system, running on the same control device.
CNC / injection molding machine data acquisition is not covered by this case.

Code example​

PDO struct definition​

The structs are laid out byte for byte according to the ESI default mapping exported in the DENI: with Pack = 1 the field order must match the mapping order exactly, and the SDK only checks that the struct is no larger than the PDO byte count. A misplaced field is not rejected; it simply reads misaligned data. In this example the input frame 0x1A00 is 23 bytes and the output frame 0x1600 is 9 bytes (each field offset is the sum of the preceding field sizes).

using System.Runtime.InteropServices;

/// <summary>
/// Panasonic MDDLT54BF servo drive input PDO (TxPDO 0x1A00)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MDDLT54BF_Input
{
public ushort ErrorCode; // 0x603F error code
public ushort StatusWord; // 0x6041 status word
public sbyte ModesOfOperationDisplay; // 0x6061 displayed mode of operation
public int ActualPosition; // 0x6064 actual position
public ushort TouchProbeStatus; // 0x60B9 probe status
public int TouchProbePos1; // 0x60BA probe position 1
public int FollowingError; // 0x60F4 following error
public uint DigitalInputs; // 0x60FD digital inputs
}

/// <summary>
/// Panasonic MDDLT54BF servo drive output PDO (RxPDO 0x1600)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MDDLT54BF_Output
{
public ushort ControlWord; // 0x6040 control word
public sbyte ModesOfOperation; // 0x6060 mode of operation
public int TargetPosition; // 0x607A target position
public ushort TouchProbeFunction; // 0x60B8 probe function
}

/// <summary>
/// EL1008 digital input PDO
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct EL1008_Input
{
public byte DigitalInputs; // 8-bit input: bit0=home X, bit1=home Y, bit2=home Z,
// bit3=gripper detection, bit4=mould-open complete signal from the injection moulding machine
}

/// <summary>
/// EL2008 digital output PDO
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct EL2008_Output
{
public byte DigitalOutputs; // 8-bit output: bit0=gripper open, bit1=gripper close, bit2=pick complete signal
}

/// <summary>
/// Three-dimensional coordinate point
/// </summary>
public struct Point3D
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }

public Point3D(double x, double y, double z)
{
X = x; Y = y; Z = z;
}
}

Control code​

using System;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
using DarraEtherCAT_Master;

class GantryRobotController
{
// Slave index (index into the master.Slaves List, from 0; differs by 1 from the 1-based slave.SlaveNum)
// The order = the actual DENI scan order and must match the topology above
const int SLAVE_EK1100 = 0;
const int SLAVE_SERVO_X = 1; // Panasonic MDDLT54BF
const int SLAVE_SERVO_Y = 2; // Panasonic MDDLT54BF
const int SLAVE_SERVO_Z = 3; // Panasonic MDDLT54BF
const int SLAVE_EL2008 = 4;
const int SLAVE_EL1008 = 5;

// Mode of operation
const sbyte MODE_CSP = 8; // Cyclic synchronous position mode

// Bus cycle (ns): default 500 µs; every per-cycle homing/interpolation increment is derived from this cycle
// Bus cycle = LoopCycle(ns) = DC Sync0 = interpolation time base; all three must be equal;
// The drive's 0x60C2 interpolation period (value x 10^exponent seconds) must also equal it (500 µs = 50 x 10^-5)
const uint CYCLE_NS = 500_000;
// Homing velocity (mm/s) and timeout
const double HOME_SPEED_MMPS = 50.0;
const double HOME_TIMEOUT_SECONDS = 30.0;
// Trapezoidal velocity profile: acceleration/deceleration each take this share of the total duration (peak velocity = each axis' max velocity)
const double ACCEL_TIME_FRACTION = 0.2;
// In-position criterion (pulses) / settling window after the time base runs out (seconds) / 0x60F4 following error limit (pulses)
const int ARRIVE_TOLERANCE_PULSES = 50;
const double SETTLE_SECONDS = 0.05;
const int MaxFollowingErrorPulses = 2000;

// Servo slave index, axis order: X=0 / Y=1 / Z=2
static readonly int[] servoSlaves = { SLAVE_SERVO_X, SLAVE_SERVO_Y, SLAVE_SERVO_Z };
static readonly int[] homeSensorBit = { 0, 1, 2 }; // EL1008 bit0=X home, bit1=Y home, bit2=Z home

// IO signal bit definitions
const byte DI_MOLD_OPEN = 0x10; // bit4: mould-open complete signal from the injection moulding machine
const byte DI_GRIPPER_CHECK = 0x08; // bit3: gripper clamp detection
const byte DO_GRIPPER_OPEN = 0x01; // bit0: gripper open
const byte DO_GRIPPER_CLOSE = 0x02; // bit1: gripper close
const byte DO_TAKEOUT_DONE = 0x04; // bit2: pick complete signal (fed back to the injection moulding machine)

// ============ Configurable parameters (set externally) ============

/// <summary> Mechanical parameter: X-axis pulses/mm </summary>
// Algorithm: encoder counts per revolution x gear ratio / screw lead (mm). The gear ratio/feed are configured on the drive:
// 0x6091:01 numerator = motor revolutions, :02 denominator = output shaft revolutions; 0x6092 feed constant (displacement per output shaft revolution).
// 0x607A target position and 0x6064 actual position use the same counting unit, so this table must agree with 0x6091/0x6092.
// Do not express direction with a negative gear ratio (both 0x6091 subindices are unsigned); set the position polarity with 0x607E bit7 instead.
public static int PulsesPerMmX { get; set; } = 10000;
/// <summary> Mechanical parameter: Y-axis pulses/mm </summary>
public static int PulsesPerMmY { get; set; } = 10000;
/// <summary> Mechanical parameter: Z-axis pulses/mm </summary>
public static int PulsesPerMmZ { get; set; } = 20000;

/// <summary> Motion parameter: max XY speed (mm/s) </summary>
public static double MaxSpeedXY { get; set; } = 2000;
/// <summary> Motion parameter: max Z speed (mm/s) </summary>
public static double MaxSpeedZ { get; set; } = 1000;

/// <summary> Pick position (mm) </summary>
public static Point3D PickPosition { get; set; } = new Point3D(100, 200, 50);
/// <summary> Place position (mm) </summary>
public static Point3D PlacePosition { get; set; } = new Point3D(300, 200, 50);
/// <summary> Safe height (mm) </summary>
public static double SafeZ { get; set; } = 150.0;

/// <summary> Soft limit lower bound (mm, relative to the mechanical zero after homing); checked every cycle on the command side </summary>
public static double[] SoftLimitMinMm { get; set; } = { 0, 0, 0 };
/// <summary> Soft limit upper bound (mm, relative to the mechanical zero after homing) </summary>
public static double[] SoftLimitMaxMm { get; set; } = { 800, 800, 300 };

// ============ Real-time state (advanced only by the one PDO cycle callback) ============
// The user thread only sets requests / waits on the completion event; all PDO writes happen inside OnPdoCycle.
static DarraEtherCAT motionMaster; // The master reference used inside the PDO callback

// Buffer reused every cycle (zero allocation on the hot path)
static readonly ushort[] statusBuf = new ushort[3];
static readonly int[] actualBuf = new int[3];
static readonly int[] followingBuf = new int[3]; // 0x60F4 following error
static readonly ushort[] cwBuf = new ushort[3];
static readonly int[] targetBuf = new int[3];

// Enable
static volatile bool servoEnable; // Master enabling switch: when false always 0x0006 + target = actual
static volatile bool enableWaitPending;
static readonly ManualResetEventSlim enableDone = new ManualResetEventSlim(false);
static readonly bool[] faultResetRequested = new bool[3];
static readonly byte[] faultResetPhase = new byte[3]; // 0=next step is the low phase, 1=next step is the high phase

// Homing (time base: start point + start time, not "a fixed number of steps per callback")
static volatile bool homingInProgress;
static readonly bool[] homeActive = new bool[3];
static readonly bool[] homeReached = new bool[3];
static readonly double[] homeStartPos = new double[3]; // Homing start point (pulses)
static readonly long[] homeStartTs = new long[3]; // Homing start timestamp
static readonly int[] homeActualPulses = new int[3]; // 0x6064 count when the home sensor is hit (mechanical zero)
static long homeDeadlineTs;
static volatile bool homeTimedOut;
static readonly ManualResetEventSlim homeDone = new ManualResetEventSlim(false);

// Interpolation
static readonly int[] moveStart = new int[3];
static readonly int[] moveDelta = new int[3];
static double moveSeconds;
static long moveStartTs;
static volatile bool moveActive;
static volatile bool moveAborted;
static volatile bool moveArrived; // Whether 0x6064 really reached position when the time base ran out
static volatile bool followAlarmLatched; // A following error limit violation is printed only once
static readonly ManualResetEventSlim moveDone = new ManualResetEventSlim(false);

// Current position (machine coordinates, mm)
static Point3D currentPosition = new Point3D(0, 0, 0);
static bool isHomed = false;

static void Main(string[] args)
{
// 1. Load the DENI
// config.deni must be exported by the master GUI after scanning the real slaves; do not edit it by hand (a topology mismatch will not reach OP)
// Build() returns a BuildResult (not the master itself); you must call .Master to get the master instance
var master = new DarraEtherCAT()
.SetENI("config.deni")
.Build()
.Master;

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

motionMaster = master;

try
{
// 2. Cycle time: set it and read it back to verify before any state transition
// The CSP interpolation step and homing step are both derived from this cycle, never assuming 1 ms
master.LoopCycle = CYCLE_NS;
if (master.LoopCycle != CYCLE_NS)
{
Console.WriteLine($"LoopCycle 设定失败: 请求 {CYCLE_NS}ns, 读回 {master.LoopCycle}ns"); // LoopCycle setup failed: {CYCLE_NS}ns requested, {master.LoopCycle}ns read back
return;
}

// 3. PreOp: configure DC Sync0 = the same cycle time on every axis
if (!master.SetState(EcState.PreOp, out string preMsg))
{ Console.WriteLine($"无法进入 PreOp: {preMsg}"); return; } // Failed to enter PreOp: {preMsg}

foreach (int idx in servoSlaves)
{
var slave = master.Slaves[idx];
// Three axes must share one Sync0 time base: refuse to enter the motion chain if there is no DC capability or the configuration fails
if (!slave.HasDC || !slave.ConfigureDC(CYCLE_NS))
{
Console.WriteLine($"从站 {idx} 无 DC 能力或 DC Sync0({CYCLE_NS}ns) 配置失败, 拒绝进入运动链路"); // Slave {idx} has no DC capability or DC Sync0({CYCLE_NS}ns) configuration failed, refusing to enter the motion link
return;
}
}

// 4. SafeOp: write a safety frame per axis before entering OP - target = actual, control word = Shutdown, so nothing jumps at the enable instant
if (!master.SetState(EcState.SafeOp, out string safeMsg))
{ Console.WriteLine($"无法进入 SafeOp: {safeMsg}"); return; } // Failed to enter SafeOp: {safeMsg}

for (int i = 0; i < servoSlaves.Length; i++)
{
ref var so = ref master.Slaves[servoSlaves[i]].PDO.OutputsMapping<MDDLT54BF_Output>();
ref readonly var si = ref master.Slaves[servoSlaves[i]].PDO.InputsMapping<MDDLT54BF_Input>();
so.ModesOfOperation = MODE_CSP; // 0x6060 = 8
so.ControlWord = 0x0006; // Shutdown: do not enable
so.TargetPosition = si.ActualPosition; // Target = actual
}

// 5. After entering OP, attach the single PDO cycle callback: enable / homing / interpolation all advance here
if (!master.SetState(EcState.OP, out string opMsg))
{
Console.WriteLine($"无法进入 OP 状态: {opMsg}"); // Failed to enter the OP state: {opMsg}
return;
}
master.Events.ProcessDataCyclicSync += OnPdoCycle;

// 6. Enable (the CiA402 handshake is done by the PDO callback; this call just waits for the result)
if (!InitializeServos())
{
Console.WriteLine("伺服未全部进入 OperationEnabled, 拒绝运动"); // Not all servos reached OperationEnabled, motion refused
return;
}

Console.WriteLine("3轴桁架机器人启动!"); // 3-axis gantry robot started!
Console.WriteLine("按 Ctrl+C 退出...\n"); // Press Ctrl+C to exit...

// 7. Run homing
Console.WriteLine("开始回原点..."); // Homing starting...
if (!HomeAllAxes()) return;

// 8. Map the IO PDO once
ref readonly var dio = ref master.Slaves[SLAVE_EL1008].PDO.InputsMapping<EL1008_Input>();
ref var dout = ref master.Slaves[SLAVE_EL2008].PDO.OutputsMapping<EL2008_Output>();

// 9. Pick-and-place loop - triggered by the mould-open signal of the injection moulding machine
var waitPosition = new Point3D(PickPosition.X, PickPosition.Y, SafeZ);

int cycleCount = 0;
bool lastMoldSignal = false;

// Initial action: open the gripper, move to the wait position
GripperOpen(ref dout);
if (!MoveToPosition(waitPosition))
{
Console.WriteLine("[报警] 初始定位等待位失败, 停机"); // [Alarm] Failed to reach the initial waiting position, machine stopped
return;
}
Console.WriteLine("就绪, 等待注塑机开模信号...\n"); // Ready, waiting for the injection molding machine mold-open signal...

while (true)
{
// When the servo loses enable or faults, stop sending targets to the axis; stop the loop and wait for a human
if (!AllServosEnabled())
{
Console.WriteLine("[报警] 有伺服掉出 OperationEnabled 或报故障, 停止取放循环"); // [Alarm] A servo dropped out of OperationEnabled or reported a fault, pick-and-place cycle stopped
return;
}

// Read the mould-open complete signal of the injection moulding machine (rising-edge triggered)
bool moldOpen = (dio.DigitalInputs & DI_MOLD_OPEN) != 0;

if (moldOpen && !lastMoldSignal)
{
// ── mould-open signal received, starting the pick ──

// Clear the pick-complete signal
dout.DigitalOutputs &= unchecked((byte)~DO_TAKEOUT_DONE);

// 1. Drop quickly from the wait position to the pick position
bool ok = MoveToPosition(PickPosition);

// 2. Close the gripper and wait for the clamp confirmation (timeout = nothing gripped, so it must not be treated as success and the lift continued)
if (ok)
{
GripperClose(ref dout);
ok = WaitGripperConfirm(dio);
if (!ok) GripperOpen(ref dout);
}

// 3. Lift to the safe height
if (ok) ok = MoveToPosition(new Point3D(PickPosition.X, PickPosition.Y, SafeZ));

// 4. Tell the injection moulding machine to close the mould only after the pick is confirmed; never signal "pick complete" when nothing was gripped
if (ok)
{
dout.DigitalOutputs |= DO_TAKEOUT_DONE;
Console.WriteLine("取件完成, 通知注塑机合模"); // Pick complete, notifying the injection molding machine to close the mold
}

// 5. Move above the place position
if (ok) ok = MoveToPosition(new Point3D(PlacePosition.X, PlacePosition.Y, SafeZ));

// 6. Descend to the place position and open the gripper
if (ok) ok = MoveToPosition(PlacePosition);
if (ok)
{
GripperOpen(ref dout);
Thread.Sleep(200);
ok = MoveToPosition(new Point3D(PlacePosition.X, PlacePosition.Y, SafeZ));
}

// 7. Return to the wait position and get ready for the next trigger
if (ok) ok = MoveToPosition(waitPosition);

cycleCount++;
Console.WriteLine(ok
? $"第 {cycleCount} 次取放循环完成, 等待下一次开模信号...\n" // Pick-and-place cycle {cycleCount} complete, waiting for the next mold-open signal...
: $"[报警] 第 {cycleCount} 次取放未完成, 已停在当前位置, 需人工确认后继续\n"); // [Alarm] Pick-and-place cycle {cycleCount} did not complete, stopped at the current position, manual confirmation required before continuing
}

lastMoldSignal = moldOpen;
Thread.Sleep(1);
}
}
finally
{
try { master.Events.ProcessDataCyclicSync -= OnPdoCycle; }
catch (Exception ex)
{
Console.WriteLine($"退订 PDO 周期回调失败: {ex.GetType().Name}: {ex.Message}"); // Failed to unsubscribe from the PDO cyclic callback: {ex.GetType().Name}: {ex.Message}
}
master.Dispose();
}
}

/// <summary>
/// Start enabling all servos
/// Only sets the request flag: the CiA402 handshake (0x06 -> 0x07 -> 0x0F, fault reset 0x0006 -> 0x0086) is advanced by the PDO callback from the status word,
/// While disabled or handshaking, the target position always equals the actual position. Motion is only released once all axes are OperationEnabled.
/// </summary>
static bool InitializeServos()
{
enableDone.Reset();
enableWaitPending = true;
servoEnable = true; // Explicit enable action; disabled by default after connecting

if (!enableDone.Wait(TimeSpan.FromSeconds(5)))
{
enableWaitPending = false;
Console.WriteLine("使能超时: 未全部进入 OperationEnabled"); // Enable timeout: not all reached OperationEnabled
return false;
}

// Mode read-back check: 0x6061 must be 8 (CSP)
for (int i = 0; i < 3; i++)
{
sbyte modeDisplay = ReadModeDisplay(i);
if (modeDisplay != MODE_CSP)
{
Console.WriteLine($"轴{i} 模式回读 {modeDisplay} ≠ CSP(8), 拒绝运动"); // Axis{i} mode read back {modeDisplay} ≠ CSP(8), motion refused
return false;
}
}

Console.WriteLine("所有松下 MDDLT54BF 伺服已使能 (CSP)"); // All Panasonic MDDLT54BF servos are enabled (CSP)
return true;
}

/// <summary>
/// Fault reset request (call only after manual confirmation)
/// Only set the request on axes genuinely in Fault ((sw & 0x4F)==0x08); healthy axes are left alone - sending to a healthy axis
/// 0x0006->0x0086 first switches it off (T8) and then performs one illegal transition.
/// The callback creates a rising edge on bit7 over two cycles: 0x0006 (low phase) -> 0x0086 (high phase).
/// </summary>
static void ResetAllFaults()
{
int n = 0;
for (int i = 0; i < faultResetRequested.Length; i++)
{
ref readonly var si = ref motionMaster.Slaves[servoSlaves[i]].PDO.InputsMapping<MDDLT54BF_Input>();
bool fault = (si.StatusWord & 0x4F) == 0x08;

faultResetPhase[i] = 0;
faultResetRequested[i] = fault;
if (fault) n++;
}
Console.WriteLine(n > 0 ? $"已请求复位 {n} 个 Fault 轴" : "没有处于 Fault 的轴, 复位请求忽略"); // Reset requested for {n} faulted axes (or: no axis is in Fault, so the reset request is ignored)
}

/// <summary>
/// Homing: the Z axis homes first (for safety), then X/Y home together once it is in position
/// All three axes are advanced by the same PDO callback; the position is computed as "start position - homing speed x elapsed time",
/// Independent of how many times the callback actually ran (dropped ticks / jitter do not change the homing speed).
/// </summary>
static bool HomeAllAxes()
{
homeDone.Reset();
homeTimedOut = false;

long now = Stopwatch.GetTimestamp();
for (int i = 0; i < 3; i++)
{
homeActive[i] = false;
homeReached[i] = false;
homeStartPos[i] = ReadActualPosition(i); // Start = current actual position
homeStartTs[i] = now;
}

homeDeadlineTs = now + (long)(HOME_TIMEOUT_SECONDS * Stopwatch.Frequency);
homeActive[2] = true; // Home Z first
homingInProgress = true;

// One Z segment + one X/Y segment, each with its own HOME_TIMEOUT_SECONDS budget
if (!homeDone.Wait(TimeSpan.FromSeconds(HOME_TIMEOUT_SECONDS * 2 + 5)))
{
homeActive[0] = homeActive[1] = homeActive[2] = false;
homingInProgress = false;
Console.WriteLine("错误: 回原点等待超时"); // Error: homing wait timed out
return false;
}

if (homeTimedOut)
{
Console.WriteLine("错误: 回原点未完成 (超时 / 掉使能 / 故障 / 复位)"); // Error: homing not complete (timeout / enable lost / fault / reset)
return false;
}

// Zero the machine coordinates; whether the encoder count is zeroed depends on the drive's homing method, so this example writes no SDO
currentPosition = new Point3D(0, 0, 0);
isHomed = true;
Console.WriteLine("回原点完成!"); // Homing complete!
return true;
}

/// <summary>
/// Homing state machine (only called inside the PDO callback): writes targetBuf directly and shares the same frame as the interpolation
/// </summary>
static void StepHoming(long now, bool allEnabled)
{
if (!allEnabled)
{
// Lost enable / faulted / in reset: abort the homing at once, target returns to actual
homeActive[0] = homeActive[1] = homeActive[2] = false;
homeTimedOut = true;
homingInProgress = false;
homeDone.Set();
return;
}

// Start homing X/Y together only after Z is in position
if (homeReached[2] && !homeActive[0] && !homeActive[1] && !homeReached[0] && !homeReached[1])
{
homeActive[0] = homeActive[1] = true;
homeStartPos[0] = actualBuf[0]; // Re-take the current actual as the start, so micro-motion during idle cannot cause a jump
homeStartPos[1] = actualBuf[1];
homeStartTs[0] = homeStartTs[1] = now;
homeDeadlineTs = now + (long)(HOME_TIMEOUT_SECONDS * Stopwatch.Frequency);
}

for (int i = 0; i < 3; i++)
{
if (!homeActive[i]) continue;

// Hit the home sensor -> target = actual, stop at once, and record that axis' mechanical zero count
if (ReadHomeSensor(i))
{
homeActive[i] = false;
homeReached[i] = true;
homeActualPulses[i] = actualBuf[i];
targetBuf[i] = actualBuf[i];
continue;
}

if (now >= homeDeadlineTs)
{
homeActive[i] = false;
homeTimedOut = true;
targetBuf[i] = actualBuf[i];
continue;
}

// Time base: distance travelled = homing velocity (mm/s) x pulses/mm x actual elapsed seconds,
// Not "a fixed number of steps per callback" - a dropped tick only loses one position update, it does not double the speed
double elapsed = (now - homeStartTs[i]) / (double)Stopwatch.Frequency;
double pos = homeStartPos[i] - HOME_SPEED_MMPS * PulsesPerMmAt(i) * elapsed;
targetBuf[i] = (int)Math.Round(pos);
}

if ((homeReached[0] && homeReached[1] && homeReached[2]) || homeTimedOut)
{
homeActive[0] = homeActive[1] = homeActive[2] = false;
homingInProgress = false;
homeDone.Set();
}
}

/// <summary>
/// Move to the target position (three-axis time-base linear interpolation)
/// Only loads the interpolation parameters; the target position is computed by the same PDO callback from the elapsed time, all three axes sharing one progress
/// (equivalent to one virtual master axis), so no axis arrives early while another is still moving.
/// Things like `steps = totalTime x 1000`, where "each callback advances exactly one step", assume 1 ms,
/// At a 500 µs cycle this multiplies the speed by 2; a time base / virtual master axis must be used.
/// </summary>
static bool MoveToPosition(Point3D target)
{
if (!isHomed)
{
Console.WriteLine("错误: 未回原点!"); // Error: not homed!
return false;
}

// The soft limit is checked on the command side (mm, relative to the mechanical zero): UI buttons cannot catch parameter edits / unit conversion errors
if (!WithinSoftLimitMm(0, target.X) || !WithinSoftLimitMm(1, target.Y) || !WithinSoftLimitMm(2, target.Z))
{
Console.WriteLine($"错误: 目标 ({target.X:F1},{target.Y:F1},{target.Z:F1}) 超出软限位"); // Error: target ({target.X:F1},{target.Y:F1},{target.Z:F1}) exceeds the soft limit
return false;
}

// Never send a target to a disabled / faulted axis (the drive would ignore it or do something unpredictable)
for (int i = 0; i < 3; i++)
{
ref readonly var si = ref motionMaster.Slaves[servoSlaves[i]].PDO.InputsMapping<MDDLT54BF_Input>();
if ((si.StatusWord & 0x4F) == 0x08)
{
Console.WriteLine($"错误: 轴{i} 驱动器故障 (0x603F=0x{si.ErrorCode:X4}), 拒绝运动"); // Error: axis{i} drive fault (0x603F=0x{si.ErrorCode:X4}), motion refused
return false;
}
if ((si.StatusWord & 0x6F) != 0x27)
{
Console.WriteLine($"错误: 轴{i} 未进入 OperationEnabled (0x6041=0x{si.StatusWord:X4}), 拒绝运动"); // Error: axis{i} did not reach OperationEnabled (0x6041=0x{si.StatusWord:X4}), motion refused
return false;
}
}

// The start always comes from 0x6064: currentPosition may be a stale value from the last abort and must not be used to compute increments
currentPosition = ReadActualPositionMm();

// Compute the displacement
double dx = target.X - currentPosition.X;
double dy = target.Y - currentPosition.Y;
double dz = target.Z - currentPosition.Z;
double distance = Math.Sqrt(dx * dx + dy * dy + dz * dz);

if (distance < 0.01) return true; // Already at the target position

// Based on the motion time of the slowest axis -> all three axes arrive together
double timeX = Math.Abs(dx) > 0.001 ? Math.Abs(dx) / MaxSpeedXY : 0;
double timeY = Math.Abs(dy) > 0.001 ? Math.Abs(dy) / MaxSpeedXY : 0;
double timeZ = Math.Abs(dz) > 0.001 ? Math.Abs(dz) / MaxSpeedZ : 0;
double maxTime = Math.Max(Math.Max(timeX, timeY), timeZ);
if (maxTime < 0.001) return true;

// Trapezoid peak = max velocity, total duration = travel/max velocity / (1 - acceleration share)
double totalSeconds = maxTime / (1.0 - ACCEL_TIME_FRACTION);

// Start = current actual position (pulses); the increment is mm × pulses/mm
for (int i = 0; i < 3; i++)
moveStart[i] = ReadActualPosition(i);
moveDelta[0] = (int)Math.Round(dx * PulsesPerMmX);
moveDelta[1] = (int)Math.Round(dy * PulsesPerMmY);
moveDelta[2] = (int)Math.Round(dz * PulsesPerMmZ);

moveSeconds = totalSeconds;
moveStartTs = Stopwatch.GetTimestamp();
moveAborted = false;
moveArrived = false;
followAlarmLatched = false;
moveDone.Reset();
moveActive = true;

if (!moveDone.Wait(TimeSpan.FromSeconds(totalSeconds + 5)))
{
moveActive = false;
currentPosition = ReadActualPositionMm();
Console.WriteLine("错误: 运动等待超时"); // Error: motion wait timed out
return false;
}

if (moveAborted)
{
currentPosition = ReadActualPositionMm(); // After an abort the coordinates must be rebuilt from the truth
Console.WriteLine("错误: 运动中掉使能 / 故障 / 超软限位 / 跟随误差超限, 已中止 (目标已回实际)"); // Error: enable lost / fault / soft limit exceeded / following error over limit during motion, aborted (target reset to actual)
return false;
}

// Time base exhausted != in position: 0x6064 must enter the settling window, otherwise it is a following error / gain problem
currentPosition = ReadActualPositionMm();
if (!moveArrived)
{
Console.WriteLine($"警告: 运动结束未进入到位窗口 ({ARRIVE_TOLERANCE_PULSES} 脉冲), 检查 0x60F4 跟随误差"); // Warning: the in-position window was not reached at the end of the move ({ARRIVE_TOLERANCE_PULSES} pulses), check following error 0x60F4
return false;
}

Console.WriteLine($"到达位置: X={currentPosition.X:F2}, Y={currentPosition.Y:F2}, Z={currentPosition.Z:F2}"); // Position reached: X={currentPosition.X:F2}, Y={currentPosition.Y:F2}, Z={currentPosition.Z:F2}
return true;
}

/// <summary> Soft limit check (mm, relative to the mechanical zero) </summary>
static bool WithinSoftLimitMm(int axis, double mm)
=> mm >= SoftLimitMinMm[axis] && mm <= SoftLimitMaxMm[axis];

/// <summary> 0x6064 -> machine coordinates (mm); homeActualPulses is only meaningful after homing </summary>
static Point3D ReadActualPositionMm()
=> new Point3D(
(ReadActualPosition(0) - homeActualPulses[0]) / (double)PulsesPerMmX,
(ReadActualPosition(1) - homeActualPulses[1]) / (double)PulsesPerMmY,
(ReadActualPosition(2) - homeActualPulses[2]) / (double)PulsesPerMmZ);

/// <summary> Whether all three axes are OperationEnabled </summary>
static bool AllServosEnabled()
{
for (int i = 0; i < 3; i++)
{
ref readonly var si = ref motionMaster.Slaves[servoSlaves[i]].PDO.InputsMapping<MDDLT54BF_Input>();
if ((si.StatusWord & 0x6F) != 0x27) return false;
}
return true;
}

/// <summary>
/// PDO cycle callback (once per CYCLE_NS): the only place that writes PDO outputs and advances the time base.
/// The enable handshake / homing / interpolation all advance here on state; user threads only set requests and wait on a completion event.
/// No periodic string building / file IO / unbounded waits inside the callback (the alarm prints only once, on the first latch), so real-time behaviour is preserved.
/// </summary>
static void OnPdoCycle(ushort mi)
{
var m = motionMaster;
if (m == null) return;

ref var outX = ref m.Slaves[SLAVE_SERVO_X].PDO.OutputsMapping<MDDLT54BF_Output>();
ref var outY = ref m.Slaves[SLAVE_SERVO_Y].PDO.OutputsMapping<MDDLT54BF_Output>();
ref var outZ = ref m.Slaves[SLAVE_SERVO_Z].PDO.OutputsMapping<MDDLT54BF_Output>();
ref readonly var inX = ref m.Slaves[SLAVE_SERVO_X].PDO.InputsMapping<MDDLT54BF_Input>();
ref readonly var inY = ref m.Slaves[SLAVE_SERVO_Y].PDO.InputsMapping<MDDLT54BF_Input>();
ref readonly var inZ = ref m.Slaves[SLAVE_SERVO_Z].PDO.InputsMapping<MDDLT54BF_Input>();

statusBuf[0] = inX.StatusWord; actualBuf[0] = inX.ActualPosition;
statusBuf[1] = inY.StatusWord; actualBuf[1] = inY.ActualPosition;
statusBuf[2] = inZ.StatusWord; actualBuf[2] = inZ.ActualPosition;
followingBuf[0] = inX.FollowingError;
followingBuf[1] = inY.FollowingError;
followingBuf[2] = inZ.FollowingError;

// ① CiA402: compute this tick's control word per axis from the status word; motion is only allowed when (sw & 0x6F)==0x27
bool allEnabled = true;
bool resetActive = false;
for (int i = 0; i < 3; i++)
{
// Treat QuickStopActive (0x07) like a field emergency stop: withdraw the enable request at once and leave only with 0x0000,
// After exiting it rests in SwitchOnDisabled and a human must confirm before re-enabling - otherwise the next tick would re-enable automatically.
if ((statusBuf[i] & 0x6F) == 0x07) servoEnable = false;

// Fault reset: low phase 0x0006 -> high phase 0x0086, creating a bit7 rising edge over two cycles.
// Never use 0x0000 (bit2=0 would hold QuickStop) / 0x0080 (same).
// Send the pulse only to axes genuinely in Fault ((sw & 0x4F)==0x08); sending it to a healthy axis switches it off first (T8),
// The 0x0086 after it is another illegal transition, wasting one torque cycle.
if (faultResetRequested[i] && (statusBuf[i] & 0x4F) != 0x08)
faultResetRequested[i] = false;

if (faultResetRequested[i])
{
resetActive = true;
if (faultResetPhase[i] == 0) { cwBuf[i] = 0x0006; faultResetPhase[i] = 1; }
else { cwBuf[i] = 0x0086; faultResetPhase[i] = 0; faultResetRequested[i] = false; }
}
else
{
cwBuf[i] = StepCiA402(statusBuf[i], servoEnable);
}

targetBuf[i] = actualBuf[i]; // Default: disabled / faulted / QuickStop / idle -> target = actual
allEnabled &= (statusBuf[i] & 0x6F) == 0x27;
}

// 0x60F4 following error limit exceeded = crash / lost steps / wrong gain; abort all motion at once (reported once only, no log spam)
bool followingErrorTooLarge = false;
for (int i = 0; i < 3; i++)
followingErrorTooLarge |= Math.Abs(followingBuf[i]) > MaxFollowingErrorPulses;
if (followingErrorTooLarge && !followAlarmLatched)
{
followAlarmLatched = true;
Console.WriteLine($"[报警] 跟随误差超限 (0x60F4 = {followingBuf[0]}/{followingBuf[1]}/{followingBuf[2]} 脉冲, 上限 {MaxFollowingErrorPulses})"); // [Alarm] Following error over limit (0x60F4 = {followingBuf[0]}/{followingBuf[1]}/{followingBuf[2]} pulses, limit {MaxFollowingErrorPulses})
}

long now = Stopwatch.GetTimestamp();

// ② Enable: notify the waiters once the handshake completes (stays true after servoEnable)
if (enableWaitPending && allEnabled)
{
enableWaitPending = false;
enableDone.Set();
}

// ③ Homing (all three axes share this callback)
if (homingInProgress)
StepHoming(now, allEnabled && !resetActive && !followingErrorTooLarge);

// ④ Interpolation: progress depends only on elapsed time, not on the actual callback count (dropped ticks do not double the speed)
if (moveActive)
{
double elapsed = (now - moveStartTs) / (double)Stopwatch.Frequency;
double p = elapsed / moveSeconds;
if (p >= 1.0) p = 1.0;
double s = TrapezoidRatio(p);

if (!allEnabled || resetActive || followingErrorTooLarge)
{
// Any axis dropping out of OperationEnabled / fault reset / following error limit exceeded: abort at once, target returns to actual
moveActive = false;
moveAborted = true;
moveDone.Set();
}
else
{
// The target is checked against the soft limit per axis on the command side (mm, relative to the mechanical zero); exceeding it stops immediately, not just blocked at the upper layer
bool limitViolation = false;
for (int i = 0; i < 3; i++)
{
int t = moveStart[i] + (int)Math.Round(moveDelta[i] * s);
if (!WithinSoftLimitMm(i, (t - homeActualPulses[i]) / (double)PulsesPerMmAt(i)))
{
limitViolation = true;
break;
}
targetBuf[i] = t;
}

if (limitViolation)
{
for (int i = 0; i < 3; i++) targetBuf[i] = actualBuf[i];
moveActive = false;
moveAborted = true;
moveDone.Set();
}
else if (p >= 1.0)
{
// Time base exhausted != in position: wait for 0x6064 to enter the settling window, or use up the window
bool arrived = true;
for (int i = 0; i < 3; i++)
arrived &= Math.Abs(actualBuf[i] - targetBuf[i]) <= ARRIVE_TOLERANCE_PULSES;

if (arrived || elapsed >= moveSeconds + SETTLE_SECONDS)
{
moveActive = false;
moveArrived = arrived;
moveDone.Set();
}
}
}
}

// ⑤ Write all three axes inside one callback -> commit in one PDO frame
// In CSP, 0x6040 stays at 0x000F: bit4 (0x0010) only means NewSetpoint in PP mode,
// Writing 0x001F in CSP makes some drives (such as the HCFA X3E) report 0x7500.
outX.ModesOfOperation = MODE_CSP;
outY.ModesOfOperation = MODE_CSP;
outZ.ModesOfOperation = MODE_CSP;
outX.ControlWord = cwBuf[0]; outX.TargetPosition = targetBuf[0];
outY.ControlWord = cwBuf[1]; outY.TargetPosition = targetBuf[1];
outZ.ControlWord = cwBuf[2]; outZ.TargetPosition = targetBuf[2];
}

/// <summary>
/// CiA 402 control word state machine (driven by the status word every cycle)
/// State check: (sw & 0x6F) running state / (sw & 0x4F)==0x08 fault
/// Always send 0x0006 (Shutdown) when enable has not been requested; never auto-enable
/// The fault reset pulse is generated by the caller over two phases, 0x0006 -> 0x0086; this function is not responsible for it
/// </summary>
static ushort StepCiA402(ushort sw, bool enable)
{
// QuickStopActive must be left first (T12 = Disable Voltage): 0x0006 in QuickStopActive
// It is an illegal transition and will be stuck in 0x07 forever. This step is independent of the enable request and must be done even when disabled.
// Note: QuickStop is a stop event; if the field treats it as an emergency stop, the upper layer should withdraw servoEnable when it sees 0x07,
// After exiting it rests in SwitchOnDisabled / ReadyToSwitchOn and must be re-enabled by a human.
if ((sw & 0x6F) == 0x07) return 0x0000;

if (!enable) return 0x0006; // Disabled: hold Shutdown
if ((sw & 0x4F) == 0x08) return 0x0006; // Fault: hold Shutdown and wait for a manual reset
switch (sw & 0x6F)
{
case 0x40: return 0x0006; // SwitchOnDisabled → Shutdown
case 0x21: return 0x0007; // ReadyToSwitchOn → Switch On
case 0x23: return 0x000F; // SwitchedOn → Enable Operation
case 0x27: return 0x000F; // OperationEnabled
case 0x00: return 0x0006; // NotReadyToSwitchOn -> wait for the automatic T1
case 0x0F: return 0x0006; // FaultReactionActive -> wait for the automatic transition to Fault
default: return 0x0000; // Illegal status word: fail-safe, cut torque
}
}

/// <summary>
/// Time-base trapezoidal velocity profile (20% acceleration / 60% constant / 20% deceleration), input and output normalised to 0..1
/// </summary>
static double TrapezoidRatio(double p)
{
const double V = 1.0 / (1.0 - ACCEL_TIME_FRACTION); // Normalised velocity of the constant-speed segment, so that s(1)=1
if (p <= 0) return 0;
if (p >= 1) return 1;
if (p < ACCEL_TIME_FRACTION) return 0.5 * V * p * p / ACCEL_TIME_FRACTION;
if (p > 1 - ACCEL_TIME_FRACTION)
{
double q = 1 - p;
return 1 - 0.5 * V * q * q / ACCEL_TIME_FRACTION;
}
return 0.5 * V * ACCEL_TIME_FRACTION + V * (p - ACCEL_TIME_FRACTION);
}

static int PulsesPerMmAt(int axis)
=> axis == 0 ? PulsesPerMmX : axis == 1 ? PulsesPerMmY : PulsesPerMmZ;

static int ReadActualPosition(int axis)
{
switch (axis)
{
case 0: return motionMaster.Slaves[SLAVE_SERVO_X].PDO.InputsMapping<MDDLT54BF_Input>().ActualPosition;
case 1: return motionMaster.Slaves[SLAVE_SERVO_Y].PDO.InputsMapping<MDDLT54BF_Input>().ActualPosition;
default: return motionMaster.Slaves[SLAVE_SERVO_Z].PDO.InputsMapping<MDDLT54BF_Input>().ActualPosition;
}
}

static sbyte ReadModeDisplay(int axis)
{
switch (axis)
{
case 0: return motionMaster.Slaves[SLAVE_SERVO_X].PDO.InputsMapping<MDDLT54BF_Input>().ModesOfOperationDisplay;
case 1: return motionMaster.Slaves[SLAVE_SERVO_Y].PDO.InputsMapping<MDDLT54BF_Input>().ModesOfOperationDisplay;
default: return motionMaster.Slaves[SLAVE_SERVO_Z].PDO.InputsMapping<MDDLT54BF_Input>().ModesOfOperationDisplay;
}
}

static bool ReadHomeSensor(int axis)
{
var dio = motionMaster.Slaves[SLAVE_EL1008].PDO.InputsMapping<EL1008_Input>();
return (dio.DigitalInputs & (1 << homeSensorBit[axis])) != 0;
}

/// <summary>
/// Open the gripper
/// </summary>
static void GripperOpen(ref EL2008_Output dout)
{
dout.DigitalOutputs = (byte)((dout.DigitalOutputs & ~(DO_GRIPPER_OPEN | DO_GRIPPER_CLOSE))
| DO_GRIPPER_OPEN);
Console.WriteLine("夹爪打开"); // Gripper open
}

/// <summary>
/// Close the gripper
/// </summary>
static void GripperClose(ref EL2008_Output dout)
{
dout.DigitalOutputs = (byte)((dout.DigitalOutputs & ~(DO_GRIPPER_OPEN | DO_GRIPPER_CLOSE))
| DO_GRIPPER_CLOSE);
Console.WriteLine("夹爪关闭"); // Gripper closed
}

/// <summary>
/// Wait for the gripper close confirmation (read live from EL1008 bit3 via PDO).
/// Timeout = nothing gripped, so return false to let the caller abort; it must not be treated as success and the lift continued.
/// </summary>
static bool WaitGripperConfirm(in EL1008_Input dio)
{
for (int i = 0; i < 500; i++)
{
if ((dio.DigitalInputs & DI_GRIPPER_CHECK) != 0)
return true;
Thread.Sleep(1);
}
Console.WriteLine("[报警] 夹爪夹紧确认超时 (500ms), 视为未夹住"); // [Alarm] Grip confirmation timed out (500ms), treated as not gripped
return false;
}
}
Units, cycle and homing
  • Position unit: 0x607A target position and 0x6064 actual position use the same count unit. This example interpolates in pulses and works in mm in the upper layer; PulsesPerMm must agree with 0x6091 on the drive side (gear ratio: :01 motor revolutions / :02 output shaft revolutions) and with 0x6092 (feed constant). Do not derive it from the bare motor encoder or from the screw lead alone.
  • Direction: both subindexes of 0x6091 are unsigned, so a negative gear ratio cannot be used to reverse the direction. The direction is set by 0x607E bit7 (position polarity) or by the wiring; after changing the polarity, re-check the sign of PulsesPerMm, the homing search direction and the soft limits.
  • Cycle: bus cycle = LoopCycle(ns) = DC Sync0 = interpolation time base; all three must have the same value. The 0x60C2 interpolation time period (value × 10^exponent seconds) must equal it — 500 µs is written as 0x60C2:01 = 50, :02 = -5.
  • Where interpolation is computed: position increments are computed on the pulse side (mm × 脉冲/mm, then rounded) and the time base on the seconds side; keep the two apart. If the increment is computed in mm and converted to pulses afterwards, the last-digit rounding error accumulates over the travel.
  • Following error: in CSP the drive closes the loop and the master only supplies a position every cycle. To reduce the following error, use velocity feedforward 0x60B1 / torque feedforward 0x60B2 (they take effect only when mapped into the RxPDO) and keep the 0x60F4 over-limit stop; in this example the in-position criterion is 0x6064 entering the settling window.
  • Homing: homing only zeroes the mechanical coordinate; it does not change the encoder count (whether the count is zeroed depends on the drive's homing method). homeActualPulses records the 0x6064 value at the moment the sensor is hit, and every later mm ↔ pulse conversion relies on it, so motion is forbidden when homing fails.

Complete example code​

This page describes a scenario; the runnable reference is Panasonic_CNC_Interpolation: it also uses Panasonic CiA 402 servos, X/Y/Z three axes, CSP mode and DC Sync0, builds the link from the real scan result in config.deni, and includes the per-axis state machine, soft limits and following-error protection. It compiles and runs. The pick-and-place sequence (injection molding machine mold-open signal, pneumatic gripper, tray positions) is the part customized for the scenario on this page; the reference project has no equivalent implementation.

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

SampleCoverage
Panasonic_CNC_InterpolationPanasonic A6B multi-axis CSP linear / circular interpolation + trapezoidal / S-curve velocity planning
Panasonic_ConveyorSyncPanasonic servo master/slave synchronization + probe capture
RobotToolChangerMulti-axis tool changer, safety interlock, slave drop monitoring and hot-plug rescan
STF-EC_CSP_PPMulti-axis stepper CSP / PP; the number of axes comes from the config.deni scan result