6-axis non-machining robot arm
Hardware configuration
- Master: Windows 10 × 1 + Intel N100 × 1
- Motion control: Leadshine 2CL3-EC507 dual-axis closed-loop stepper drive × 3 (CiA 402, with built-in DI)
- End effector: vacuum suction cup × 1 + vacuum generator × 1
- Sensors: photoelectric sensor × 1 + vacuum pressure switch × 1
Three Leadshine dual-axis closed-loop stepper drives are used: one drive controls two joints, so 3 drives cover 6 axes. The drive's built-in DI reads the photoelectric and vacuum sensors in real time over PDO; DO controls the vacuum over SDO (not real-time, but sufficient). Closed-loop steppers resist step loss, which suits light-load (≤2 kg) non-machining scenarios.
Cost breakdown
| Category | Model / specification | Reference unit price (¥) | Qty | Subtotal (¥) |
|---|---|---|---|---|
| Dual-axis closed-loop stepper drive | Leadshine 2CL3-EC507 | 900 | 3 | 2,700 |
| Closed-loop stepper motor (J1-J3) | 57 closed-loop stepper | 120 | 3 | 360 |
| Closed-loop stepper motor (J4-J6) | 42 closed-loop stepper | 60 | 3 | 180 |
| Photoelectric sensor | Through-beam NPN | 30 | 1 | 30 |
| Vacuum pressure switch | SMC ZSE30A | 80 | 1 | 80 |
| Vacuum suction cup | SMC ZP2 | 100 | 1 | 100 |
| Vacuum generator | Small vacuum generator | 80 | 1 | 80 |
| Industrial PC | Intel N100 class | 1,500 | 1 | 1,500 |
| Reference total for the line | ≈ ¥5,030 |
The prices above are reference prices (RMB) for the core components; they exclude the arm structure, cables, pneumatic fittings, solenoid valves and so on.
Performance figures
- Positioning accuracy: ±0.05 mm (closed-loop stepper)
- Maximum speed: 150~250 °/s (varies per joint; J1/J3 are 180 °/s, see
MaxSpeedDpsin the code) - Repeatability: ±0.02 mm
- Closed-loop step-loss protection: alarms automatically on stall
Application scenario
Palletizing station on an electronics assembly line. A 6-axis closed-loop stepper arm with a vacuum suction cup picks PCB boards / small parts and stacks them.
The large joints (J1-J3) use 57 closed-loop steppers for enough torque; the small joints (J4-J6) use 42 closed-loop steppers to cut cost and inertia.
Each dual-axis drive controls two joints (Axis A + Axis B), reducing the number of devices and the wiring complexity. Suits light-load (≤2 kg) non-machining scenarios.
Slave-to-axis mapping: 3 drives = 3 slaves (master.Slaves[0]~[2]; the slave index SlaveNum is 1-based while the Slaves index is 0-based); two axes per slave = Axis A / Axis B, 6 axes in total. The axis index in the code is 0-based (J1=0 … J6=5): master.Slaves[i / 2] selects the slave, i % 2 == 0 selects Axis A, otherwise Axis B.
Capability boundary: the master handles cyclic synchronous position (CSP) setpoint issue, CiA 402 state machine progression, PDO/SDO reads and writes, and slave diagnostics (slave.IsLost; the SlaveOffline / SlaveOnline events support drop detection and hot-plug recovery). Inverse kinematics, trajectory planning, soft limits and safety interlocking are the upper-level controller's responsibility — the trapezoidal interpolation, soft limits and arrival criteria in this example are implemented at the application layer.
Code example
PDO struct definitions
using System.Runtime.InteropServices;
/// <summary>
/// Leadshine 2CL3-EC507 dual-axis drive output PDO (RxPDO)
/// CSP mode: 0x1600 (Axis A) + 0x1610 (Axis B), SM2
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct DualAxis_Output
{
// Axis A (object index 0x60xx)
public ushort ControlWord_A; // 0x6040 control word
public int TargetPosition_A; // 0x607A target position (pulses)
public ushort TouchProbeFunc_A; // 0x60B8 probe function
// Axis B (object index 0x68xx)
public ushort ControlWord_B; // 0x6840 control word
public int TargetPosition_B; // 0x687A target position (pulses)
public ushort TouchProbeFunc_B; // 0x68B8 probe function
}
/// <summary>
/// Leadshine 2CL3-EC507 dual-axis drive input PDO (TxPDO)
/// 0x1A00 (Axis A) + 0x1A10 (Axis B), SM3
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct DualAxis_Input
{
// Axis A (object index 0x60xx)
public ushort LastErrorCode_A; // 0x603F latest error code
public ushort StatusWord_A; // 0x6041 status word
public sbyte ModesOfOpDisplay_A; // 0x6061 current mode of operation
public int ActualPosition_A; // 0x6064 actual position (pulses)
public ushort TouchProbeStatus_A; // 0x60B9 probe status
public int TouchProbe1PosVal_A; // 0x60BA probe 1 latched position
public uint DigitalInputs_A; // 0x60FD digital inputs
public int AdditionalPos_A; // 0x5500:05 additional position
// Axis B (object index 0x68xx)
public ushort LastErrorCode_B; // 0x683F latest error code
public ushort StatusWord_B; // 0x6841 status word
public sbyte ModesOfOpDisplay_B; // 0x6861 current mode of operation
public int ActualPosition_B; // 0x6864 actual position (pulses)
public ushort TouchProbeStatus_B; // 0x68B9 probe status
public int TouchProbe1PosVal_B; // 0x68BA probe 1 latched position
public uint DigitalInputs_B; // 0x68FD digital inputs
public int AdditionalPos_B; // 0x5D00:05 additional position
}
/// <summary>
/// Joint angles
/// </summary>
public class JointAngles
{
public double[] Angles { get; set; } = new double[6];
public double J1 { get => Angles[0]; set => Angles[0] = value; }
public double J2 { get => Angles[1]; set => Angles[1] = value; }
public double J3 { get => Angles[2]; set => Angles[2] = value; }
public double J4 { get => Angles[3]; set => Angles[3] = value; }
public double J5 { get => Angles[4]; set => Angles[4] = value; }
public double J6 { get => Angles[5]; set => Angles[5] = value; }
}
Both structs are Pack = 1: the output is 8 bytes per axis (2 + 4 + 2), 16 bytes for both axes; the input is 23 bytes per axis (2 + 2 + 1 + 4 + 2 + 4 + 4 + 4), 46 bytes for both axes. The field order must match the ESI RxPDO / TxPDO entry order byte for byte — one wrong field shifts the data of every axis after it. Before mapping you can check the process image size with slave.OutputsByteCount / slave.InputsByteCount; if the struct is larger than the process image, the mapping entry throws instead of silently truncating.
Control code
using System;
using System.Diagnostics;
using System.Threading;
using DarraEtherCAT_Master;
class RobotArmController
{
// Slave index: 3 dual-axis drives daisy-chained directly
const int SLAVE_DRIVE1 = 0; // Drive 1: Axis A = J1 (base rotation), Axis B = J2 (shoulder)
const int SLAVE_DRIVE2 = 1; // Drive 2: Axis A = J3 (elbow), Axis B = J4 (wrist rotation)
const int SLAVE_DRIVE3 = 2; // Drive 3: Axis A = J5 (wrist pitch), Axis B = J6 (end rotation)
// CiA 402 state machine control word
const ushort CW_SHUTDOWN = 0x0006; // Ready to Switch On
const ushort CW_SWITCH_ON = 0x0007; // Switched On
const ushort CW_ENABLE_OPERATION = 0x000F; // Operation Enabled
const ushort CW_DISABLE_VOLTAGE = 0x0000; // The only legal exit from QuickStopActive (T12)
// CiA 402 status word mask
const ushort SW_FAULT = 0x0008; // bit3: fault
const ushort SW_FAULT_MASK = 0x004F; // Mask used to judge Fault: (sw & 0x4F) == 0x08
const ushort SW_OP_ENABLED_MASK = 0x006F; // Bits to check: 0,1,2,3,5,6
const ushort SW_OP_ENABLED_VAL = 0x0027; // Operation Enabled state value
// Bus cycle (ns): default 500 µs; set it and read it back to verify before any state transition
// 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, and must also equal it (500 µs = 50 x 10^-5)
const uint CYCLE_NS = 500_000;
const sbyte MODE_CSP = 8; // 0x6060 / 0x6860 = 8, cyclic synchronous position
// In-position criterion (pulses) and the settling window after the time base runs out (seconds): the time base finishing != the axis really being in position
const int ARRIVE_TOLERANCE_PULSES = 50;
const double SETTLE_SECONDS = 0.05;
// Trapezoidal velocity profile: acceleration/deceleration each take this share of the total duration (peak velocity = joint max velocity)
const double ACCEL_TIME_FRACTION = 0.2;
// Sensor assignment (using the drive's built-in DI, read live through the 0x60FD/0x68FD PDO)
// Drive 1 Axis A 0x60FD: photoelectric sensor (the J1 drive is near the pick table)
// Drive 3 Axis B 0x68FD: vacuum pressure switch (the J6 drive is near the end effector)
// ⚠ Check the bit numbers against the drive's ESI / manual DI mapping before using them: vendors allocate the bits of 0x60FD differently
// They are not uniform (some place limits/home on bit16~19, others on bit0~2); do not copy bit16 from this example;
// The two constants have the same value because they read different axes of different slaves, not the same object.
const uint DI_WORKPIECE = 0x00010000; // 0x60FD bit16: general input (photoelectric)
const uint DI_VACUUM_OK = 0x00010000; // 0x68FD bit16: general input (vacuum pressure)
// Vacuum control (0x60FE is not in the default PDO, so write it over SDO); likewise check the bit numbers against the vendor DO mapping
const uint DO_VACUUM_ON = 0x00010000; // 0x60FE:01 bit16: vacuum on
const uint DO_VACUUM_BLOW = 0x00020000; // 0x60FE:01 bit17: blow-off release
// ============ Configurable parameters (set externally) ============
/// <summary>
/// Pulses per degree (J1-J3: 57 motor high resolution, J4-J6: 42 motor)
/// Algorithm: encoder counts per revolution x gear ratio / 360. The gear ratio is configured at drive object 0x6091:
/// :01 = motor revolutions (numerator), :02 = output shaft revolutions (denominator); the gearhead numerator < denominator (CiA 402-2).
/// 0x607A / 0x6064 use the same counting unit (position units after the gear ratio and the 0x6092 feed constant),
/// So this table must be filled in from the actual 0x6091/0x6092 configuration, not guessed from the bare motor encoder.
/// Do not express direction with a negative gear ratio (both 0x6091 subindices are unsigned); set the position polarity with 0x607E bit7 instead.
/// </summary>
public static int[] PulsesPerDegree { get; set; } = { 1000, 1000, 800, 500, 500, 400 };
/// <summary>Max speed (deg/s)</summary>
public static double[] MaxSpeedDps { get; set; } = { 180, 150, 180, 200, 200, 250 };
/// <summary>Joint lower limit (degrees)</summary>
public static double[] JointLimitsMin { get; set; } = { -170, -90, -120, -180, -120, -360 };
/// <summary>Joint upper limit (degrees)</summary>
public static double[] JointLimitsMax { get; set; } = { 170, 90, 120, 180, 120, 360 };
/// <summary>Home position</summary>
public static JointAngles HomePosition { get; set; } = new JointAngles { J1 = 0, J2 = 0, J3 = 0, J4 = 0, J5 = 0, J6 = 0 };
/// <summary>Pick position</summary>
public static JointAngles PickPosition { get; set; } = new JointAngles { J1 = 45, J2 = -30, J3 = 60, J4 = 0, J5 = -30, J6 = 0 };
/// <summary>Place position</summary>
public static JointAngles PlacePosition { get; set; } = new JointAngles { J1 = -45, J2 = -30, J3 = 60, J4 = 0, J5 = -30, J6 = 0 };
/// <summary>Lift offset (J2 offset, degrees)</summary>
public static double LiftOffset { get; set; } = 20;
/// <summary>Vacuum confirmation timeout (ms)</summary>
public static int VacuumTimeoutMs { get; set; } = 500;
/// <summary>Maximum vacuum-pick retry count</summary>
public static int VacuumRetryMax { get; set; } = 3;
// Current joint angles
static JointAngles currentAngles = new JointAngles();
static bool isHomed = false;
static volatile bool isRunning = false;
// ============ Real-time state (advanced only by the PDO cycle callback) ============
// Interpolation parameters for one motion: filled in by MoveToJointPosition, then consumed by the SDK's PDO cycle callback
// Compute progress from the elapsed time and write the 6 axis target positions (CSP); no user-space spin sets the pace.
static DarraEtherCAT motionMaster; // The master reference used inside the PDO callback
static volatile bool moveActive; // Whether a motion is currently executing
static volatile bool moveAborted; // Lost enable / faulted / exceeded the soft limit during motion
static volatile bool moveArrived; // Whether 0x6064 really reached position when the time base ran out
static JointAngles moveStart, moveTarget;
static double moveDurationSeconds;
static long moveStartTs;
static readonly object moveLock = new object();
static readonly ManualResetEventSlim moveDone = new ManualResetEventSlim(false);
// Enable
static readonly ManualResetEventSlim enableDone = new ManualResetEventSlim(false);
static volatile bool enableWaitPending;
static volatile bool servoEnable; // Master enabling switch: when false always 0x0006 + target = actual
static readonly bool[] faultResetRequested = new bool[6];
static readonly byte[] faultResetPhase = new byte[6]; // 0=next step is the low phase, 1=next step is the high phase
// Buffer reused every cycle (index = J1..J6, zero allocation on the hot path)
static readonly ushort[] swBuf = new ushort[6];
static readonly int[] actBuf = new int[6];
static readonly ushort[] cwBuf = new ushort[6];
static readonly int[] tgtBuf = new int[6];
static void Main(string[] args)
{
// 1. Load the DENI (exported by the master GUI after scanning the real slaves; do not edit it by hand)
// 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
// Interpolation progress is computed from the elapsed time; this cycle is the pacing reference and also the DC Sync0 period
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: 6 axes all in CSP
// This PDO mapping has no mode word, so 0x6060 / 0x6860 must be set to 8 over SDO and read back to verify
if (!master.SetState(EcState.PreOp, out string preMsg))
{ Console.WriteLine($"无法进入 PreOp: {preMsg}"); return; } // Failed to enter PreOp: {preMsg}
for (int i = 0; i < 3; i++)
{
var slave = master.Slaves[i];
if (!SetCspMode(slave, 0x6060) || !SetCspMode(slave, 0x6860))
{
Console.WriteLine($"驱动器 {i} CSP 模式设定失败 (0x6060 / 0x6860)"); // Drive {i} failed to set CSP mode (0x6060 / 0x6860)
return;
}
// 6 axes must share one Sync0 time base: refuse to enter the motion chain if there is no DC capability or the configuration fails,
// Otherwise each axis acts at its own sampling instant and the interpolated line/arc falls apart.
// HasDC is only the ESC hardware bit; you must also check whether the ESI declares DC-Sync0 (HasEsiDcSync),
// Otherwise a station where the ESC reports DC capable but the ESI declares nothing will refuse to enter OP without giving an error code.
if (!slave.HasDC || !slave.HasEsiDcSync || !slave.ConfigureDC(CYCLE_NS))
{
Console.WriteLine($"驱动器 {i} 无 DC 能力或 ESI 未声明 DC-Sync0, 或 DC Sync0({CYCLE_NS}ns) 配置失败, 多轴同步无法保证"); // Drive {i} has no DC capability or the ESI does not declare DC-Sync0, or DC Sync0({CYCLE_NS}ns) configuration failed, so multi-axis synchronization cannot be guaranteed
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 < 3; i++)
{
ref var o = ref master.Slaves[i].PDO.OutputsMapping<DualAxis_Output>();
ref readonly var inp = ref master.Slaves[i].PDO.InputsMapping<DualAxis_Input>();
o.ControlWord_A = 0x0006; o.TargetPosition_A = inp.ActualPosition_A;
o.ControlWord_B = 0x0006; o.TargetPosition_B = inp.ActualPosition_B;
}
// 5. Enter OP and attach the single PDO cycle callback (enable / interpolation all advance inside this one callback)
if (!master.SetState(EcState.OP, out string opMsg))
{
Console.WriteLine($"无法进入 OP 状态: {opMsg}"); // Failed to enter the OP state: {opMsg}
return;
}
isRunning = true;
master.Events.ProcessDataCyclicSync += OnPdoCycle;
// 6. Enable (the CiA402 handshake is done by the PDO callback; this call just waits for all axes to reach OperationEnabled)
if (!InitializeAxes())
{
Console.WriteLine("未全部进入 OperationEnabled, 拒绝运动"); // Not all reached OperationEnabled, motion refused
// If it is a drive Fault: after the field confirms mechanical safety, call ResetFaults() to send the bit7 reset pulse, then re-enable
return;
}
Console.WriteLine("6轴机器手启动!"); // 6-axis robot arm started!
Console.WriteLine("按 Ctrl+C 退出...\n"); // Press Ctrl+C to exit...
// 7. Run homing
Console.WriteLine("开始回原点..."); // Homing starting...
HomeAllJoints();
// 8. Map the sensor PDO (the reference points into the process image, which the master loop keeps up to date)
ref readonly var drive1In = ref master.Slaves[SLAVE_DRIVE1].PDO.InputsMapping<DualAxis_Input>();
ref readonly var drive3In = ref master.Slaves[SLAVE_DRIVE3].PDO.InputsMapping<DualAxis_Input>();
// 9. Triggered palletising loop
int cycleCount = 0;
while (true)
{
// ---- Wait for the photoelectric trigger: drive 1 Axis A DI detects the workpiece arriving ----
Console.WriteLine("等待工件..."); // Waiting for a workpiece...
while ((drive1In.DigitalInputs_A & DI_WORKPIECE) == 0)
{
// While idle, any axis dropping out of OperationEnabled must be reported; do not sit waiting blindly for a signal
if (!AllAxesEnabled(master))
{
Console.WriteLine("[报警] 待机期间有轴掉出 OperationEnabled, 停止码垛循环"); // [Alarm] An axis dropped out of OperationEnabled while idle, palletizing cycle stopped
return;
}
Thread.Sleep(5);
}
Console.WriteLine($"[周期 {++cycleCount}] 检测到工件, 开始取料"); // [Cycle {++cycleCount}] Workpiece detected, starting the pick
// ---- Move to the pick position ----
if (!MoveToJointPosition(master, PickPosition, 50))
{
AbortPickCycle(master, "取料定位失败", releaseVacuum: true); // Pick positioning failed
continue;
}
// ---- Pick up the workpiece (with confirmation and retry) ----
bool picked = false;
for (int retry = 0; retry < VacuumRetryMax && !picked; retry++)
{
// SDO write to drive 3 DO: vacuum on (0x60FE:01, UDINT). A write failure must stop the machine,
// Otherwise it waits forever for a vacuum that will never build
if (!SetVacuum(master, DO_VACUUM_ON))
{
AbortPickCycle(master, "真空 DO 写入失败", releaseVacuum: true); // Vacuum DO write failed
break;
}
// Wait for the vacuum pressure switch confirmation (drive 3 Axis B DI)
if (WaitVacuumConfirm(drive3In))
{
picked = true;
Console.WriteLine("真空吸取确认"); // Vacuum grip confirmed
break;
}
Console.WriteLine($"真空未达标, 重试 ({retry + 1}/{VacuumRetryMax})"); // Vacuum not reached, retrying ({retry + 1}/{VacuumRetryMax})
SetVacuum(master, DO_VACUUM_BLOW);
Thread.Sleep(100);
SetVacuum(master, 0);
Thread.Sleep(200);
}
if (!picked)
{
AbortPickCycle(master, "吸取失败", releaseVacuum: true); // Pickup failed
continue;
}
// ---- Lift ----
var liftPosition = new JointAngles
{
J1 = PickPosition.J1, J2 = PickPosition.J2 + LiftOffset,
J3 = PickPosition.J3, J4 = PickPosition.J4,
J5 = PickPosition.J5, J6 = PickPosition.J6
};
if (!MoveToJointPosition(master, liftPosition, 30))
{
// The workpiece is already on the suction cup: hold the vacuum and stop the line for a human; never blow it off and lose the part here
Console.WriteLine("[报警] 抬升失败, 工件仍在吸盘上, 停在当前位置等待人工处理"); // [Alarm] Lift failed, the workpiece is still on the suction cup, stopped at the current position awaiting manual handling
return;
}
// ---- Check vacuum in transit (live PDO read) ----
if ((drive3In.DigitalInputs_B & DI_VACUUM_OK) == 0)
{
AbortPickCycle(master, "搬运途中真空丢失 (工件已掉落)", releaseVacuum: true); // Vacuum lost in transit (the workpiece has dropped)
continue;
}
// ---- Move to the place position ----
if (!MoveToJointPosition(master, PlacePosition, 80))
{
Console.WriteLine("[报警] 放料定位失败, 工件仍在吸盘上, 停在当前位置等待人工处理"); // [Alarm] Place positioning failed, the workpiece is still on the suction cup, stopped at the current position awaiting manual handling
return;
}
// ---- Release the workpiece ----
SetVacuum(master, DO_VACUUM_BLOW);
Thread.Sleep(100);
SetVacuum(master, 0);
Console.WriteLine("工件释放"); // Workpiece released
// ---- Return to home, wait for the next trigger ----
if (!MoveToJointPosition(master, HomePosition, 50))
{
Console.WriteLine("[报警] 回原点失败, 需人工检查"); // [Alarm] Homing failed, manual inspection required
continue;
}
Console.WriteLine($"[周期 {cycleCount}] 码垛完成\n"); // [Cycle {cycleCount}] Palletizing complete
}
}
finally
{
isRunning = false;
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>
/// Write the vacuum DO (0x60FE:01, UDINT). An SDO failure must be reported; it must not be treated as success and continued.
/// </summary>
static bool SetVacuum(DarraEtherCAT master, uint value)
{
// Slave.CoE is a protocol instance that may be null (when the slave has no CoE mailbox), so check before calling
var coe = master.Slaves[SLAVE_DRIVE3].CoE;
if (coe == null)
{
Console.WriteLine("[报警] 驱动器3 不支持 CoE, 无法写 0x60FE:01"); // [Alarm] Drive3 does not support CoE, 0x60FE:01 cannot be written
return false;
}
if (coe.SDOWrite(0x60FE, 1, BitConverter.GetBytes(value)))
return true;
Console.WriteLine($"[报警] 真空 DO 写入失败 (0x60FE:01 = 0x{value:X8}), 检查邮箱与对象可写性"); // [Alarm] Vacuum DO write failed (0x60FE:01 = 0x{value:X8}), check the mailbox and whether the object is writable
return false;
}
/// <summary>
/// Abort this pick-and-place round: release the vacuum and return to the safe position as needed; report failures honestly and do not silently continue to the next round
/// </summary>
static void AbortPickCycle(DarraEtherCAT master, string reason, bool releaseVacuum)
{
Console.WriteLine($"[报警] {reason}, 中止本轮"); // [Alarm] {reason}, aborting this round
if (releaseVacuum) SetVacuum(master, 0);
if (!MoveToJointPosition(master, HomePosition, 30))
Console.WriteLine("[报警] 回安全位失败, 轴保持当前位置 (目标=实际), 需人工检查"); // [Alarm] Failed to return to the safe position, the axis holds its current position (target = actual), manual inspection required
}
/// <summary>
/// PDO cycle callback: the SDK calls it automatically once per bus cycle (= LoopCycle).
/// The only place that writes the PDO: the CiA402 control word and all 6 target positions are written here and committed in one frame.
/// Interpolation progress is computed from the elapsed time (not "one step per callback"), so cycle changes / dropped ticks do not change the speed.
/// </summary>
static void OnPdoCycle(ushort mi)
{
var master = motionMaster;
if (master == null || !isRunning) return;
try
{
ref readonly var d1In = ref master.Slaves[SLAVE_DRIVE1].PDO.InputsMapping<DualAxis_Input>();
ref readonly var d2In = ref master.Slaves[SLAVE_DRIVE2].PDO.InputsMapping<DualAxis_Input>();
ref readonly var d3In = ref master.Slaves[SLAVE_DRIVE3].PDO.InputsMapping<DualAxis_Input>();
// Index = J1..J6
swBuf[0] = d1In.StatusWord_A; actBuf[0] = d1In.ActualPosition_A;
swBuf[1] = d1In.StatusWord_B; actBuf[1] = d1In.ActualPosition_B;
swBuf[2] = d2In.StatusWord_A; actBuf[2] = d2In.ActualPosition_A;
swBuf[3] = d2In.StatusWord_B; actBuf[3] = d2In.ActualPosition_B;
swBuf[4] = d3In.StatusWord_A; actBuf[4] = d3In.ActualPosition_A;
swBuf[5] = d3In.StatusWord_B; actBuf[5] = d3In.ActualPosition_B;
// ① CiA402 control word: motion is only allowed when (sw & 0x6F)==0x27
bool allEnabled = true;
bool resetActive = false;
for (int i = 0; i < 6; i++)
{
// 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): a healthy axis receiving 0x0006 is first
// Switch-off (T8), and the 0x0086 after it is another illegal transition - one wasted torque cycle followed by a re-enable.
if (faultResetRequested[i] && (swBuf[i] & SW_FAULT_MASK) != SW_FAULT)
faultResetRequested[i] = false; // No longer in Fault: the request is void, do not send the pulse
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(swBuf[i], servoEnable);
}
tgtBuf[i] = actBuf[i]; // Default: disabled / faulted / QuickStop / idle -> target = actual
allEnabled &= (swBuf[i] & SW_OP_ENABLED_MASK) == SW_OP_ENABLED_VAL;
}
if (enableWaitPending && allEnabled)
{
enableWaitPending = false;
enableDone.Set();
}
// ② Interpolation: progress depends only on elapsed time, not on how many times the callback actually ran
if (moveActive)
{
double elapsed = (Stopwatch.GetTimestamp() - moveStartTs) / (double)Stopwatch.Frequency;
double p = elapsed / moveDurationSeconds;
if (p >= 1.0) p = 1.0;
double s = TrapezoidRatio(p);
if (!allEnabled || resetActive)
{
// Any axis dropping out of OperationEnabled or in a fault reset: abort at once, target returns to actual
moveActive = false;
moveAborted = true;
moveDone.Set();
}
else
{
bool limitViolation = false;
for (int i = 0; i < 6; i++)
{
double deg = moveStart.Angles[i] + (moveTarget.Angles[i] - moveStart.Angles[i]) * s;
// The soft limit is checked every cycle on the command side (the start point can also be an out-of-range actual position),
// It is not enough to block this in the UI / upper-layer buttons - parameter changes and unit conversion errors must both be caught here
if (!WithinSoftLimit(i, deg))
{
limitViolation = true;
break;
}
tgtBuf[i] = (int)Math.Round(deg * PulsesPerDegree[i]);
}
if (limitViolation)
{
for (int i = 0; i < 6; i++) tgtBuf[i] = actBuf[i];
moveActive = false;
moveAborted = true;
moveDone.Set();
}
else if (p >= 1.0)
{
// Time base exhausted != the axis really being in position: wait for 0x6064 to converge on the target, or use up the settling window
bool arrived = true;
for (int i = 0; i < 6; i++)
arrived &= Math.Abs(actBuf[i] - tgtBuf[i]) <= ARRIVE_TOLERANCE_PULSES;
if (arrived || elapsed >= moveDurationSeconds + SETTLE_SECONDS)
{
moveActive = false;
moveArrived = arrived;
moveDone.Set();
}
}
}
}
// ③ Write all 6 axes inside one callback -> commit in one PDO frame
// In CSP, 0x6040 / 0x6840 stay at 0x000F: bit4 (0x0010) only means NewSetpoint in PP mode,
// Writing 0x001F in CSP makes some drives report 0x7500.
ref var d1Out = ref master.Slaves[SLAVE_DRIVE1].PDO.OutputsMapping<DualAxis_Output>();
ref var d2Out = ref master.Slaves[SLAVE_DRIVE2].PDO.OutputsMapping<DualAxis_Output>();
ref var d3Out = ref master.Slaves[SLAVE_DRIVE3].PDO.OutputsMapping<DualAxis_Output>();
d1Out.ControlWord_A = cwBuf[0]; d1Out.TargetPosition_A = tgtBuf[0];
d1Out.ControlWord_B = cwBuf[1]; d1Out.TargetPosition_B = tgtBuf[1];
d2Out.ControlWord_A = cwBuf[2]; d2Out.TargetPosition_A = tgtBuf[2];
d2Out.ControlWord_B = cwBuf[3]; d2Out.TargetPosition_B = tgtBuf[3];
d3Out.ControlWord_A = cwBuf[4]; d3Out.TargetPosition_A = tgtBuf[4];
d3Out.ControlWord_B = cwBuf[5]; d3Out.TargetPosition_B = tgtBuf[5];
}
catch (Exception ex)
{
// A callback exception is not thrown back to the master thread; it aborts the current motion and wakes the waiters
moveActive = false;
moveAborted = true;
moveDone.Set();
Console.WriteLine($"PDO 周期回调异常: {ex.GetType().Name}: {ex.Message}"); // PDO cyclic callback exception: {ex.GetType().Name}: {ex.Message}
}
}
/// <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 & SW_OP_ENABLED_MASK) == 0x07) return CW_DISABLE_VOLTAGE;
if (!enable) return CW_SHUTDOWN; // Disabled: hold Shutdown
if ((sw & SW_FAULT_MASK) == SW_FAULT) return CW_SHUTDOWN; // Fault: wait for a manual reset
switch (sw & SW_OP_ENABLED_MASK)
{
case 0x40: return CW_SHUTDOWN; // SwitchOnDisabled → Shutdown
case 0x21: return CW_SWITCH_ON; // ReadyToSwitchOn → Switch On
case 0x23: return CW_ENABLE_OPERATION; // SwitchedOn → Enable Operation
case 0x27: return CW_ENABLE_OPERATION; // OperationEnabled
case 0x00: return CW_SHUTDOWN; // NotReadyToSwitchOn -> wait for the automatic T1
case 0x0F: return CW_SHUTDOWN; // FaultReactionActive -> wait for the automatic transition to Fault
default: return CW_DISABLE_VOLTAGE; // Illegal status word: fail-safe, cut torque
}
}
/// <summary> Soft limit check (degrees): used every cycle on the command side, independent of the UI / upper-layer buttons </summary>
static bool WithinSoftLimit(int axis, double deg)
=> deg >= JointLimitsMin[axis] && deg <= JointLimitsMax[axis];
/// <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);
}
/// <summary> 0x6060 / 0x6860: write CSP(8) and read it back to verify (this PDO mapping contains no mode word) </summary>
static bool SetCspMode(DarraEtherCAT.Slave slave, ushort modeIndex)
{
var coe = slave.CoE;
if (coe == null) return false;
if (!coe.SDOWrite(modeIndex, 0, new byte[] { unchecked((byte)MODE_CSP) })) return false;
// SDORead(index, subindex, out structured result, completeAccess=false)
coe.SDORead(modeIndex, 0, out SdoReadResult r, false);
return r.Ok && r.Data != null && r.Data.Length == 1 && r.Data[0] == MODE_CSP;
}
/// <summary> Read the actual position of one joint (pulses), index 0..5 = J1..J6 </summary>
static int ReadActualPulses(int axis)
{
ref readonly var inp = ref motionMaster.Slaves[axis / 2].PDO.InputsMapping<DualAxis_Input>();
return axis % 2 == 0 ? inp.ActualPosition_A : inp.ActualPosition_B;
}
/// <summary> Whether all 6 axes are OperationEnabled </summary>
static bool AllAxesEnabled(DarraEtherCAT master)
{
for (int i = 0; i < 6; i++)
{
ref readonly var inp = ref master.Slaves[i / 2].PDO.InputsMapping<DualAxis_Input>();
ushort sw = i % 2 == 0 ? inp.StatusWord_A : inp.StatusWord_B;
if ((sw & SW_OP_ENABLED_MASK) != SW_OP_ENABLED_VAL) return false;
}
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, wasting torque.
/// The callback creates a rising edge on bit7 over two cycles: 0x0006 (low phase) -> 0x0086 (high phase).
/// </summary>
static void ResetFaults()
{
int n = 0;
for (int i = 0; i < faultResetRequested.Length; i++)
{
ref readonly var inp = ref motionMaster.Slaves[i / 2].PDO.InputsMapping<DualAxis_Input>();
ushort sw = i % 2 == 0 ? inp.StatusWord_A : inp.StatusWord_B;
bool fault = (sw & SW_FAULT_MASK) == SW_FAULT;
faultResetPhase[i] = 0;
faultResetRequested[i] = fault;
if (fault) n++;
}
Console.WriteLine(n > 0
? $"已请求复位 {n} 个 Fault 轴" // Reset requested for {n} faulted axes
: "没有处于 Fault 的轴, 复位请求忽略"); // No axis is in Fault, the reset request is ignored
}
/// <summary>
/// Wait for the vacuum pressure switch confirmation (read live via drive 3 Axis B DI PDO)
/// </summary>
static bool WaitVacuumConfirm(in DualAxis_Input drive3In)
{
int waited = 0;
while (waited < VacuumTimeoutMs)
{
if ((drive3In.DigitalInputs_B & DI_VACUUM_OK) != 0)
return true;
Thread.Sleep(10);
waited += 10;
}
return false;
}
/// <summary>
/// Wait for all 6 axes to reach OperationEnabled
/// The handshake itself is advanced by the PDO callback from the status word (0x06 -> 0x07 -> 0x0F, fault reset 0x0006 -> 0x0086);
/// While disabled or handshaking, the target position always equals the actual position.
/// </summary>
static bool InitializeAxes()
{
enableDone.Reset();
enableWaitPending = true;
servoEnable = true; // Explicit enable action; disabled by default after connecting, always sending 0x0006
if (!enableDone.Wait(TimeSpan.FromSeconds(5)))
{
enableWaitPending = false;
// On timeout, report each axis' state honestly instead of silently continuing
string[] axisNames = { "J1", "J2", "J3", "J4", "J5", "J6" };
for (int i = 0; i < 6; i++)
{
ref readonly var inp = ref motionMaster.Slaves[i / 2].PDO.InputsMapping<DualAxis_Input>();
ushort sw = i % 2 == 0 ? inp.StatusWord_A : inp.StatusWord_B;
Console.WriteLine($"{axisNames[i]} StatusWord=0x{sw:X4} 未进入 OperationEnabled"); // {axisNames[i]} StatusWord=0x{sw:X4} did not reach OperationEnabled
}
return false;
}
Console.WriteLine("6轴全部使能 (CSP 模式)"); // All 6 axes enabled (CSP mode)
return true;
}
/// <summary>
/// Homing (simplified: treats the power-on position as zero, no mechanical motion)
/// </summary>
static void HomeAllJoints()
{
// Simplified: treats the power-on position as zero
//
// Production homing guide:
// Switch to Homing mode first (0x6060 = 6; this page's PDO mapping has no mode word, so SDO is the only way), steps:
// 1. Write 0x6060 (Modes of Operation) = 6 (Homing Mode)
// 2. Write 0x6098 (Homing Method) to choose a homing method, for example:
// - Method 33: home to the current position (no mechanical motion)
// - Method 1: homing on the negative limit switch
// - Method 2: homing on the positive limit switch
// - Method 35: home to the Index pulse
// 3. Write 0x6099:01 (Homing Speed - Search Switch) to set the switch-search speed
// 4. Write 0x6099:02 (Homing Speed - Search Zero) to set the zero-search speed
// 5. Write 0x609A (Homing Acceleration) to set the homing acceleration
// 6. Set ControlWord bit4 = 1 to start homing
// 7. Poll StatusWord bit12 (Homing Attained) until it completes
// 8. When finished switch back to CSP mode: write 0x6060 = 8
//
// Example (single axis):
// master.Slaves[0].CoE.SDOWrite(0x6060, 0, new byte[] { 6 }); // switch to Homing mode
// master.Slaves[0].CoE.SDOWrite(0x6098, 0, new byte[] { 33 }); // method 33: home to the current position
// // ... set velocity and acceleration ...
// // Set ControlWord bit4=1 to start, then wait for StatusWord bit12=1
// master.Slaves[0].CoE.SDOWrite(0x6060, 0, new byte[] { 8 }); // switch back to CSP mode
// Read the actual position of each axis as the zero, target = actual -> produces no motion at all (never write 0 directly and cause a jump)
for (int i = 0; i < 6; i++)
currentAngles.Angles[i] = ReadActualPulses(i) / (double)PulsesPerDegree[i];
isHomed = true;
Console.WriteLine("回原点完成! (简化模式, 以上电位置为零位)"); // Homing complete! (simplified mode, the power-on position taken as zero)
}
/// <summary>
/// Move to the target joint positions (6-axis synchronised interpolation, CSP mode)
/// Only loads the interpolation parameters; the 6-axis targets are computed by the same PDO callback with the same progress and sent in one frame.
/// `steps = maxTime x 1000` assumes 1 ms; at a 500 µs cycle the step count halves, so it must be driven off the time base.
/// </summary>
static bool MoveToJointPosition(DarraEtherCAT master, JointAngles target, double speedPercent)
{
if (!isHomed)
{
Console.WriteLine("错误: 未回原点!"); // Error: not homed!
return false;
}
// 0% does not mean "do not move": a division by zero would run at maximum speed, so it must be explicitly rejected; >100% is clamped to 100%
if (speedPercent <= 0)
{
Console.WriteLine($"错误: 速度百分比非法 ({speedPercent})"); // Error: invalid speed percentage ({speedPercent})
return false;
}
if (speedPercent > 100) speedPercent = 100;
// Check the joint limits
for (int i = 0; i < 6; i++)
{
if (!WithinSoftLimit(i, target.Angles[i]))
{
Console.WriteLine($"错误: J{i + 1} 超出限位 ({target.Angles[i]:F1}°)!"); // Error: J{i + 1} exceeds the limit ({target.Angles[i]:F1}°)!
return false;
}
}
// Check for a drive fault (CiA 402: (sw & 0x4F) == 0x08)
for (int i = 0; i < 3; i++)
{
ref readonly var input = ref master.Slaves[i].PDO.InputsMapping<DualAxis_Input>();
if ((input.StatusWord_A & SW_FAULT_MASK) == SW_FAULT)
{
Console.WriteLine($"错误: J{i * 2 + 1} 驱动器故障 (ErrorCode=0x{input.LastErrorCode_A:X4})!"); // Error: J{i * 2 + 1} drive fault (ErrorCode=0x{input.LastErrorCode_A:X4})!
return false;
}
if ((input.StatusWord_B & SW_FAULT_MASK) == SW_FAULT)
{
Console.WriteLine($"错误: J{i * 2 + 2} 驱动器故障 (ErrorCode=0x{input.LastErrorCode_B:X4})!"); // Error: J{i * 2 + 2} drive fault (ErrorCode=0x{input.LastErrorCode_B:X4})!
return false;
}
}
// All 6 axes must be OperationEnabled before motion is allowed
if (!AllAxesEnabled(master))
{
Console.WriteLine("错误: 有轴未进入 OperationEnabled, 拒绝运动"); // Error: an axis did not reach OperationEnabled, motion refused
return false;
}
// Start = the current actual position converted to degrees (no jump)
var start = new JointAngles();
for (int i = 0; i < 6; i++)
start.Angles[i] = ReadActualPulses(i) / (double)PulsesPerDegree[i];
// Compute the longest motion time (based on the slowest joint, so they arrive together)
double maxTime = 0;
for (int i = 0; i < 6; i++)
{
double delta = Math.Abs(target.Angles[i] - start.Angles[i]);
double speed = MaxSpeedDps[i] * speedPercent / 100.0;
if (speed > 0)
{
double time = delta / speed;
if (time > maxTime) maxTime = time;
}
}
// Trapezoid peak = joint max velocity, total duration = travel/max velocity / (1 - acceleration share)
double duration = Math.Max(maxTime, 0.02) / (1.0 - ACCEL_TIME_FRACTION);
// Load this motion's interpolation parameters and hand them to the PDO cycle callback to advance on the time base (real-time CSP command).
lock (moveLock)
{
moveStart = start;
moveTarget = target;
moveDurationSeconds = duration;
moveStartTs = Stopwatch.GetTimestamp();
moveAborted = false;
moveArrived = false;
moveDone.Reset();
moveActive = true;
}
// Wait for the callback to finish (wait on the completion event; no user-space spin sets the control pace)
if (!moveDone.Wait(TimeSpan.FromSeconds(duration + 5)))
{
moveActive = false;
// After an abort/timeout, rebuild "current angle" from the 0x6064 truth instead of reusing the previous command target
for (int i = 0; i < 6; i++)
currentAngles.Angles[i] = ReadActualPulses(i) / (double)PulsesPerDegree[i];
Console.WriteLine("错误: 运动等待超时"); // Error: motion wait timed out
return false;
}
if (moveAborted)
{
for (int i = 0; i < 6; i++)
currentAngles.Angles[i] = ReadActualPulses(i) / (double)PulsesPerDegree[i];
Console.WriteLine("错误: 运动中轴掉出 OperationEnabled / 故障 / 超软限位, 已中止 (目标已回实际位置)"); // Error: an axis dropped out of OperationEnabled / fault / soft limit exceeded during motion, aborted (target reset to the actual position)
return false;
}
// Time base exhausted but 0x6064 never entered the settling window = the following error is too large (gain/feedforward/load problem), so it must not count as success
if (!moveArrived)
{
for (int i = 0; i < 6; i++)
currentAngles.Angles[i] = ReadActualPulses(i) / (double)PulsesPerDegree[i];
Console.WriteLine($"警告: 运动结束时关节未进入到位窗口 ({ARRIVE_TOLERANCE_PULSES} 脉冲), 检查 0x60F4 跟随误差"); // Warning: the joint did not enter the in-position window at the end of the move ({ARRIVE_TOLERANCE_PULSES} pulses), check following error 0x60F4
return false;
}
// Update the current position
for (int i = 0; i < 6; i++)
currentAngles.Angles[i] = target.Angles[i];
Console.WriteLine($"到达位置: J1={target.J1:F1}°, J2={target.J2:F1}°, J3={target.J3:F1}°"); // Position reached: J1={target.J1:F1}°, J2={target.J2:F1}°, J3={target.J3:F1}°
return true;
}
}
- Position unit:
0x607Atarget position and0x6064actual position must use the same count unit. This example computes everything in pulses (counts); angles are converted only in the upper layer. Do not write angles straight into0x607A. - Pulses per degree:
PulsesPerDegree[i]= encoder counts per revolution × gear ratio ÷ 360. The gear ratio is configured at0x6091::01numerator = motor revolutions,:02denominator = output shaft revolutions (CiA 402-2); for a reduction gear the numerator is smaller than the denominator. Both subindices are unsigned, so direction cannot be expressed by a negative gear ratio; set it with0x607Ebit7 (position polarity) or with the wiring. After flipping direction with0x607E, the signs in this table and inJointLimitsMin/Maxmust change as well. - Cycle: bus cycle =
LoopCycle(ns) = DC Sync0 = interpolation time base; all three must hold the same value. The drive's0x60C2interpolation time period (value × 10^exponent seconds) must equal it — 500 µs is written as0x60C2:01 = 50,:02 = -5; do not leave the factory default of 1 ms. - Following error: in CSP the drive closes the position loop, and the master supplies only a position each cycle. To reduce following error use velocity feed-forward
0x60B1/ torque feed-forward0x60B2(they take effect only when mapped into the RxPDO) and monitor it with0x60F4(this example's input PDO does not map that object; to read it, first add it to the TxPDO per the ESI and update the struct accordingly); the arrival criterion in this example reads0x6064and compares it with the target. - Homing: the example's "power-up position is zero" is for commissioning only.
JointLimitsMin/Maxare absolute limits relative to the mechanical zero; before production operation you must home with0x6098(method 33 only sets the current position to zero, which is not the same as finding the mechanical zero), otherwise limit protection means nothing.
Complete example code
This page describes a scenario (3 dual-axis drives = 3 slaves = 6 axes, vacuum-cup palletizing), and the repository has no project that matches it one to one. The closest runnable reference is the real sample RobotToolChanger: also a CSP robot arm (organized as J1~J6, with the axis count set by armSlaves), with position hold when a slave drops out, emergency stop, following-error monitoring and a tool changer, and built on the same Darra.EtherCAT.Master class library.
- Project directory, under the repository's open-source sample folder:
Darra_EtherCAT_开源案例/Windows/CSharp/RobotToolChanger - Six-axis CiA 402 can use the
slave.CoE.CiA402high-level wrapper (the property may be null; check it first); this page uses the lower-levelPDO+CoE.SDOWriteto explain the PDO / state machine details. - For multi-axis interpolation see also Panasonic_CNC_Interpolation.