CiA 402 — servo drive helper
CiA 402 (IEC 61800-7-204) is a CoE-based device profile for servo drives. It wraps drive state machine management, operation mode switching and motion parameter access.
CiA 402 runs on top of CoE (SDO) and is available only when the slave supports CoE.
Obtain the CiA402& reference through slave.GetCiA402().
- Cyclic synchronous position mode fixes
0x6060 = 8; under CSP do not write0x001F(bit4 is the NewSetpoint of PP/HM). - Judge the state with
(statusWord & 0x6F):== 0x27= OperationEnabled; judge a fault with(statusWord & 0x4F) == 0x08(0x4F only looks at faults and cannot be used to judge the running state). - When the drive is not enabled, is handshaking, or a group is stopped, the target position always equals the actual position, so it cannot jump.
- Fault reset relies on a rising edge of bit7 and must keep bit2=1 (release QuickStop) at the same time: in PDO, send it as
0x0006 → 0x0086over two cycles; sending only0x0080leaves bit2=0, which pulls in QuickStop, and also cannot produce a rising edge. Do not Sleep inside the PDO callback. - Multiple axes send per axis inside the same PDO callback (
SetPDOCallbackSync); do not start one thread per axis; keep the axis order fixed (for example ascendingSlaveIndex) and do not let the iteration order of an unordered container decide the send order. - The single-axis PP
0x1Fmust not be copied to CSP / synchronized axes; synchronized axes use CSP + DC only.
State query
StateDrive()
StateCiA402 StateDrive() const;
Get the drive state (parses the StatusWord).
Returns:
StateCiA402— the parsed drive state;Unknownwhen the status word cannot be matched
To parse a status word you already hold offline, use the static method:
static StateCiA402 ParseState(uint16_t statusword);
Related structure:
enum class StateCiA402 : int {
NotReadyToSwitchOn = 0, // Not ready
SwitchOnDisabled = 1, // Enabling is disabled
ReadyToSwitchOn = 2, // Ready
SwitchedOn = 3, // Enabled
OperationEnabled = 4, // Operation enable
QuickStopActive = 5, // Quick stopping
FaultReactionActive = 6, // Handling a fault
Fault = 7, // Fault
Unknown = 99 // Unknown (the status word matches nothing)
};
Statusword()
uint16_t Statusword() const;
Read the status word (0x6041, the CiA 402 standard status word, which contains the state machine flags). Boolean judgements: TargetReached() / HasFault() / HasWarning() / IsRemote() / HomingAttained() / HomingError().
Returns:
uint16_t— raw status word; a failed read falls back to0(indistinguishable from a real 0; to tell a failed read apart useTryReadObject<uint16_t>(0x6041, 0))
Example:
auto& cia = master.GetSlave(1).GetCiA402();
printf("StatusWord: 0x%04X\n", cia.Statusword());
printf("目标到达: %s\n", cia.TargetReached() ? "是" : "否"); // Target reached: %s (yes / no)
printf("有故障: %s\n", cia.HasFault() ? "是" : "否"); // Fault present: %s (yes / no)
Controlword()
uint16_t Controlword() const;
void Controlword(uint16_t v) const;
Read / write the CiA 402 standard control word (0x6040). Use it when you advance the state machine by hand; prefer the high-level wrappers Enable() / QuickStop() / FaultReset().
Parameters:
v— control word value to write (command constants are in the "Control word command constants" section)
Returns:
- read overload:
uint16_t— raw control word; a failed read falls back to0 - write overload:
void— a failed write returns no status (to confirm the result usecoe.SDOWrite)
IsTargetReached()
bool IsTargetReached() const;
Equivalent to TargetReached(): reads bit10 of the status word (0x6041) to decide whether the target has been reached. IsInPosition() is an alias of the same implementation, and IsMoving() is its negation.
Returns:
bool—true= the drive reports the target reached; when the status word read fails it falls back to0, so the call returnsfalse(indistinguishable from "not reached"; to tell them apart useTryReadStatusword())
GetStatusWord()=Statusword(): the return value and the failure semantics are completely identical, and a failed read likewise falls back to0GetControlWord()=Controlword(): read overload, and a failed read likewise falls back to0
Both are convenience names for the same implementation; they add no caching and no validation.
State machine
StateCiA402 transitions are driven by combinations of ControlWord bits, and the application layer normally does not write them itself: Enable() walks the whole enable chain, Disable() / DisableOperation() / QuickStop() handle the exit, and FaultReset() clears the fault.
To advance it by hand, write the control word according to the mapping below: Shutdown 0x0006 → ReadyToSwitchOn; Switch On 0x0007 → SwitchedOn; Enable Operation 0x000F → OperationEnabled; Disable Voltage 0x0000 → SwitchOnDisabled; Quick Stop 0x0002 → QuickStopActive; Fault Reset uses two phases 0x0006 → 0x0086 (rising edge on bit7, with bit2=1 releasing QuickStop).
Leaving QuickStopActive cannot go straight to Shutdown 0x0006 (that command is valid only in SwitchOnDisabled): first send Disable Voltage 0x0000 to return to SwitchOnDisabled, then walk the enable chain 0x0006 → 0x0007 → 0x000F again.
Do not compare the whole status word value to judge the state: parse it with StateDrive(), or use (statusWord & 0x6F) == 0x27 for OperationEnabled and (statusWord & 0x4F) == 0x08 for a fault.
Enable and stop
Enable(int maxRetries = 10)
bool Enable(int maxRetries = 10) const;
Enables the drive: internally it completes the full SwitchOnDisabled → ReadyToSwitchOn → SwitchedOn → OperationEnabled sequence per CiA 402-2, the Fault reset and the QuickStop recovery (including the 0x605A option code check), without exposing state machine details in the C++ layer.
Parameters:
maxRetries— maximum number of retries (default 10)
Returns:
bool—true= enabled up to OperationEnabled,false= failure/timeout. CallStateDrive()for the detailed enumerated state.
Disable()
void Disable() const;
Disables the servo (Disable Voltage). Equivalent to ControlWord = 0x00, entering the SwitchOnDisabled state.
DisableOperation()
void DisableOperation() const;
Disables operation: falls back to the SwitchedOn state; the motor stays powered but outputs no torque.
QuickStop()
void QuickStop() const;
Quick stop: ControlWord = 0x02, entering QuickStopActive. For the exit path from QuickStopActive see the "State machine" section.
Example:
auto& cia = master.GetSlave(1).GetCiA402();
cia.DisableOperation(); // Keep powered, output no torque
cia.QuickStop(); // Quick stop
cia.Disable(); // Drop the enable and enter SwitchOnDisabled
FaultReset()
bool FaultReset() const;
Fault reset. Per CiA 402-2 T15 / ETG.6010 §5.2 it performs a two-phase control word write: first write the low phase 0x0006 (bit7=0, with bit2=1 releasing QuickStop; do not write 0x00, which would trip QuickStop by mistake), wait 1 ms, then write the high phase 0x0086 (rising edge on bit7) — writing only the high phase produces no rising edge and the fault will not be cleared.
Returns:
bool—true= both control word writes succeeded;false= either phase failed/threw (the reset signal is incomplete, the fault will not be cleared, and the failure is logged as a Warning)
FaultReset() contains a 1 ms delay and blocks the calling thread. In a PDO setting write one phase per cycle instead, and do not put it in the cycle callback.
Example:
auto& cia = master.GetSlave(1).GetCiA402();
// Enable in one call (the full state machine runs internally)
if (cia.Enable()) {
printf("使能成功\n"); // Enabled successfully
} else {
printf("使能失败, 当前状态: %d\n", static_cast<int>(cia.StateDrive())); // Enable failed, current state: %d
}
// Fault handling
if (cia.HasFault()) {
if (!cia.FaultReset())
printf("故障复位未完成(控制字写入失败,故障不会被清除)\n"); // Fault reset did not complete (the control word write failed, so the fault will not be cleared)
}
Operation modes
OperationMode()
std::optional<ModeCiA402> OperationMode() const; // Read the mode of operation (0x6061)
void OperationMode(ModeCiA402 m) const; // Set the mode of operation (0x6060)
Writing the target mode (0x6060) returns void and does not read back to confirm; to check whether the device followed, read the mode display object (0x6061) with OperationMode().
Returns:
- read overload:
std::optional<ModeCiA402>— the current mode of 0x6061;std::nulloptwhen the read fails or the value is 0 (unspecified) or an illegal vendor number (ModeCiA402has no None member; do not treat a failure as mode 0) - write overload:
void— writes 0x6060, no read-back confirmation
Related structure:
enum class ModeCiA402 : int8_t {
PP = 1, // Profile position mode
VL = 2, // Velocity mode
PV = 3, // Profile velocity mode
PT = 4, // Profile torque mode
HM = 6, // Homing mode
IP = 7, // Interpolated position mode
CSP = 8, // Cyclic synchronous position mode
CSV = 9, // Cyclic synchronous velocity mode
CST = 10, // Cyclic synchronous torque mode
CSTCA = 11 // Cyclic synchronous torque mode with commutation angle
};
IsModeSupported()
bool IsModeSupported(ModeCiA402 mode) const;
Checks whether the drive supports the given operation mode (queries 0x6502).
Example:
auto& cia = master.GetSlave(1).GetCiA402();
// Set to CSP mode
cia.OperationMode(ModeCiA402::CSP);
// Verify
if (auto mode = cia.OperationMode())
printf("当前模式: %d\n", static_cast<int>(*mode)); // Current mode: %d
// Check the supported modes
if (cia.IsModeSupported(ModeCiA402::CSP)) {
printf("支持 CSP 模式\n"); // CSP mode supported
}
Mode switch convenience entry points
Each of the five parameterless functions performs exactly one OperationMode(...) write (0x6060) with no read-back confirmation; whether the device actually followed the target mode still has to be checked by reading OperationMode() (0x6061).
| Category | Method | Type or return type | Read/write | Description |
|---|---|---|---|---|
| Mode switch | SetProfilePositionMode() | void | write-only | Equivalent to OperationMode(ModeCiA402::PP), writes 0x6060 = 1 |
| Mode switch | SetProfileVelocityMode() | void | write-only | Equivalent to OperationMode(ModeCiA402::PV), writes 0x6060 = 3 |
| Mode switch | SetCyclicSyncPositionMode() | void | write-only | Equivalent to OperationMode(ModeCiA402::CSP), writes 0x6060 = 8 |
| Mode switch | SetCyclicSyncVelocityMode() | void | write-only | Equivalent to OperationMode(ModeCiA402::CSV), writes 0x6060 = 9 |
| Mode switch | SetCyclicSyncTorqueMode() | void | write-only | Equivalent to OperationMode(ModeCiA402::CST), writes 0x6060 = 10 |
Motion parameters
Position / velocity / torque (read)
int32_t PositionActual() const; // Actual position (0x6064)
int32_t VelocityActual() const; // Actual velocity (0x606C)
int16_t TorqueActual() const; // Actual torque (0x6077)
Target values (read/write)
int32_t TargetPosition() const;
void TargetPosition(int32_t v) const; // Target position (0x607A)
int32_t TargetVelocity() const;
void TargetVelocity(int32_t v) const; // Target velocity (0x60FF)
int16_t TargetTorque() const;
void TargetTorque(int16_t v) const; // Target torque (0x6071)
A failed read falls back to 0, indistinguishable from a real 0. To separate them use TryReadPositionActual() / TryReadVelocityActual() / TryReadObject<T>(), and use value only when Ok().
PositionActual() and TargetPosition() read and write 0x6064 / 0x607A respectively, and both are the drive's own position units — usually encoder counts, possibly mm / rad after conversion by the 0x6091 gear ratio and the 0x6092 feed constant. The SDK performs no unit conversion and will not check the units for you. 0x607A and 0x6064 must use the same unit, otherwise the target value you send and the actual value you read back are not comparable (this shows up as a constant position offset or spurious limit trips). For the unit definition see 0x6091 and 0x6092 in the device ESI / manual.
Convenience entry points (thin wrappers)
The names below are only more direct names for the read/write entry points above; they perform no unit conversion, no limit checking and no failure conversion:
| Category | Method | Type or return type | Read/write | Description |
|---|---|---|---|---|
| Target values | SetTargetPosition(int32_t pos) | void | write-only | Equivalent to the TargetPosition(pos) write overload, writes 0x607A; a failed write reports no status |
| Target values | SetTargetVelocity(int32_t vel) | void | write-only | Equivalent to the TargetVelocity(vel) write overload, writes 0x60FF; a failed write reports no status |
| Actual values | GetActualVelocity() | int32_t | read-only | Equivalent to VelocityActual(), reads 0x606C; a failed read falls back to 0, indistinguishable from a real 0 |
| Homing | GetHomePosition() | int32_t | read-only | Equivalent to PositionActual(), returns the current actual position (0x6064); it is not HomeOffset (0x607C) and does not mean homing is complete (for that see IsHomingComplete()) |
| Profile | SetProfileVelocity(uint32_t vel) | void | write-only | Equivalent to the ProfileVelocity(vel) write overload (0x6081) |
| Profile | SetProfileAcceleration(uint32_t acc) | void | write-only | Equivalent to the ProfileAcceleration(acc) write overload (0x6083) |
| Profile | SetProfileDeceleration(uint32_t dec) | void | write-only | Equivalent to the ProfileDeceleration(dec) write overload (0x6084) |
GetActualPosition() = PositionActual(), returns the current actual position from 0x6064, and a failed read likewise falls back to 0; to tell a failed read apart use TryReadPositionActual().
Profile and extended parameters (read/write)
uint32_t ProfileVelocity() const; void ProfileVelocity(uint32_t v) const; // 0x6081
uint32_t ProfileAcceleration() const; void ProfileAcceleration(uint32_t v) const; // 0x6083
uint32_t ProfileDeceleration() const; void ProfileDeceleration(uint32_t v) const; // 0x6084
uint32_t QuickStopDeceleration() const; void QuickStopDeceleration(uint32_t v) const; // 0x6085
uint8_t Polarity() const; void Polarity(uint8_t v) const; // 0x607E: bit6 = velocity inversion, bit7 = position inversion
int16_t MotionProfileType() const; void MotionProfileType(int16_t v) const; // 0x6086
int32_t SoftwarePositionLimitMin() const; void SoftwarePositionLimitMin(int32_t v) const; // 0x607D:01
int32_t SoftwarePositionLimitMax() const; void SoftwarePositionLimitMax(int32_t v) const; // 0x607D:02
MotionProfileType values: 0 = linear ramp, 1 = sine, 2 = S-curve.
The two 0x607D values are only software limit objects written to the drive; the SDK will not stop a target position for you. TargetPosition() sent every cycle (and NewSetpoint() for PP) should each be checked against the same pair of limits on the application side, and an out-of-range value should not be sent and should raise an alarm; doing the check only once in the UI means a trajectory jump or an external parameter change sends the out-of-range target straight into the drive.
PP mode helper
NewSetpoint()
void NewSetpoint(int32_t position, bool relative = false) const;
PP mode: send a new positioning command: first write the target position (0x607A), then set ControlWord Bit4 (NewSetpoint) automatically.
Parameters:
position— target position (drive-side user units, the same unit asPositionActual())relative— defaultfalse(absolute positioning); whentrue, Bit6 (Relative) is also set and positioning is by relative distance
ClearNewSetpoint()
void ClearNewSetpoint() const;
Clears the NewSetpoint bit. PP handshake: after TargetReached(), call this function to complete the Set-point Ack, then send the next positioning command.
StartHoming()
void StartHoming() const;
void StartHoming(int8_t method) const;
void StartHoming(HomingMethodCiA402 method) const;
HM mode: start homing (sets ControlWord Bit4). The two overloads that take a method first write the homing method to 0x6098 and then start.
Parameters:
method— homing method: a rawint8_tnumber (including negative vendor-specific values), or the standardHomingMethodCiA402enum
IsHomingComplete()
bool IsHomingComplete() const;
Whether homing is complete: HomingAttained() is true and HomingError() is false.
Homing parameters
std::optional<HomingMethodCiA402> HomingMethod() const; // Homing method (0x6098) standard enum
void HomingMethod(int8_t v) const; // Write the raw code (including vendor-specific negative values)
void HomingMethod(HomingMethodCiA402 v) const; // Write the standard enum
std::optional<int8_t> HomingMethodRaw() const; // Read the raw code (sbyte)
int32_t HomeOffset() const; void HomeOffset(int32_t v) const; // Home offset (0x607C)
uint32_t HomingSpeedSearch() const; void HomingSpeedSearch(uint32_t v) const; // Homing search velocity (0x6099:01)
uint32_t HomingSpeedZero() const; void HomingSpeedZero(uint32_t v) const; // Homing zero-pulse velocity (0x6099:02)
uint32_t HomingAcceleration() const; void HomingAcceleration(uint32_t v) const; // Homing acceleration (0x609A)
HomingMethodCiA402 numbers follow CiA 402 / ETG.6010: 0 = no homing; 1..14, 17..30, 33..35, 37 are standard methods; 15/16/31/32/36 are reserved numbers and negative values are vendor-specific methods — HomingMethod() parses both of those into std::nullopt rather than fabricating an enum member. 33/34 = index pulse only, 35/37 = the current position is home. For the full enum see the "Homing method enum" section; to work with raw numbers use HomingMethodRaw() (returns std::nullopt on a failed read, and does not swallow a failure into 0 = no homing). The free function TryParseHomingMethod(int8_t raw) can also parse a raw number into the enum on its own (reserved / vendor numbers return std::nullopt).
TouchProbe and digital IO
uint16_t TouchProbeStatus() const; // Status (0x60B9)
int32_t TouchProbePositiveEdge() const; // Positive edge position (0x60BA)
int32_t TouchProbeNegativeEdge() const; // Negative edge position (0x60BB)
void ConfigureTouchProbe(uint16_t function) const; // Configuration (0x60B8)
uint32_t DigitalInputs() const; // Digital input (0x60FD)
uint32_t DigitalOutputs() const; // Digital output (0x60FE:1)
void DigitalOutputs(uint32_t v) const; // Set a digital output
TouchProbe convenience entry points
| Category | Method | Type or return type | Read/write | Description |
|---|---|---|---|---|
| TouchProbe | GetTouchProbeStatus() | uint16_t | read-only | Equivalent to TouchProbeStatus(), reads 0x60B9; a failed read falls back to 0, indistinguishable from a real 0 |
| TouchProbe | GetTouchProbePosition() | int32_t | read-only | Equivalent to TouchProbePositiveEdge(), reads the positive edge position 0x60BA (not the negative edge 0x60BB); a failed read falls back to 0, indistinguishable from a real 0 |
Extended motion parameters
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Torque | MaxTorque() | uint16_t | read/write | Maximum torque (0x6072), in thousandths of the rated torque |
| Torque | MotorRatedTorque() | uint32_t | read/write | Motor rated torque (0x6076), in mNm |
| Torque | PositiveTorqueLimit() / NegativeTorqueLimit() | uint16_t | read/write | Positive / negative torque limits (0x60E0 / 0x60E1), in thousandths of rated |
| Offset | PositionOffset() | int32_t | read/write | Position offset (0x60B0), added to the target position under CSP |
| Offset | VelocityOffset() | int32_t | read/write | Velocity offset (0x60B1), added to the target velocity under CSV |
| Offset | TorqueOffset() | int16_t | read/write | Torque offset (0x60B2), added to the target torque under CST |
| Interpolation | InterpolationTimePeriodValue() | uint8_t | read/write | Interpolation time period value (0x60C2:01) |
| Interpolation | InterpolationTimePeriodIndex() | int8_t | read/write | Interpolation time period exponent (0x60C2:02); cycle = value × 10^exponent seconds |
| Limit | SoftwarePositionLimitMin() / SoftwarePositionLimitMax() | int32_t | read/write | Software position limit lower / upper bound (0x607D:01 / 0x607D:02) |
| Option code | QuickStopOptionCode() | int16_t | read/write | Quick stop option code (0x605A). 0=disable the drive, 1/2=decelerate and stop, 5/6=decelerate and hold. A failed read = -32768 sentinel |
| Option code | ShutdownOptionCode() | int16_t | read/write | Shutdown option code (0x605B). 0..7 decide which state to stop in after Shutdown and along which deceleration ramp. A failed read = -32768 sentinel |
| Option code | DisableOperationOptionCode() | int16_t | read/write | Disable operation option code (0x605C). 0..7 decide the behaviour and ramp of Disable Operation. A failed read = -32768 sentinel |
| Option code | HaltOptionCode() | int16_t | read/write | Halt option code (0x605D). The behaviour when control word bit8 (Halt) takes effect. A failed read = -32768 sentinel |
| Option code | FaultReactionOptionCode() | int16_t | read/write | Fault reaction option code (0x605E). 0..2 decide the deceleration method during the fault reaction. A failed read = -32768 sentinel |
Example:
auto& cia = master.GetSlave(1).GetCiA402();
// Torque configuration
cia.MaxTorque(1000); // Maximum torque = 100% of rated
cia.PositiveTorqueLimit(500); // Torque limit in both directions = 50% of rated
cia.NegativeTorqueLimit(500);
// CSP / CSV offset superimposition
cia.PositionOffset(100);
cia.VelocityOffset(50);
// Interpolation period (1 ms = 1 x 10^(-3) s)
cia.InterpolationTimePeriodValue(1);
cia.InterpolationTimePeriodIndex(-3);
// Software position limits
cia.SoftwarePositionLimitMin(-1000000);
cia.SoftwarePositionLimitMax(1000000);
// Quick stop option (5 = hold after decelerating, direct recovery allowed)
cia.QuickStopOptionCode(5);
The actual cycle of 0x60C2 is InterpolationTimePeriodValue × 10^InterpolationTimePeriodIndex seconds (the example 1 × 10^-3 = 1 ms). Under CSP / CSV / CST this cycle should match the master PDO cycle; when the two differ, the drive interprets target values on the wrong interpolation beat, which shows up as a larger following error or a scaled velocity. Note that the units differ: Slave::ConfigureDC() takes nanoseconds (1'000'000 = 1 ms), while 0x60C2 computes to seconds.
TxPDO data validity
TxPdoDataInvalid()
bool TxPdoDataInvalid() const;
std::optional<bool> TryTxPdoDataInvalid() const;
Whether the TxPDO data is invalid (0x603E). false only means the value was read this time and is 0. true can mean either that the slave reported invalid or that the read failed (a failed read is treated as invalid, fail-closed). To separate the two cases, use TryTxPdoDataInvalid(): std::nullopt is unknown and must not be treated as valid.
Returns:
bool—true= data invalid (or a failed read treated as invalid);false= read this time and the value is 0std::optional<bool>—std::nullopt= read failed / not supported (validity unknown); a value = the slave's real value
Example:
auto& cia = master.GetSlave(1).GetCiA402();
if (!cia.TxPdoDataInvalid()) {
int32_t pos = cia.PositionActual(); // The data is valid and safe to use
}
Synchronization functions
uint16_t SynchronizationSettings() const; void SynchronizationSettings(uint16_t v) const; // 0x60D9:01
uint16_t DriveSyncStatus() const; // 0x60DA, read-only
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Synchronization functions | SynchronizationSettings() | uint16_t | read/write | Synchronization settings (0x60D9:01), synchronization enable bitmask |
| Synchronization functions | DriveSyncStatus() | uint16_t | read-only | Drive synchronization status (0x60DA), whether the drive has synchronized to the master clock |
Example:
auto& cia = master.GetSlave(1).GetCiA402();
// Read the drive synchronisation state
uint16_t syncStatus = cia.DriveSyncStatus();
printf("同步状态: 0x%04X\n", syncStatus); // Sync status: 0x%04X
// Configure the synchronisation settings
cia.SynchronizationSettings(0x0001);
Homing method enum
enum class HomingMethodCiA402 : int8_t {
None = 0, // No homing (keep the current position)
NegativeLimitSwitch = 1, // Negative limit switch + index pulse
PositiveLimitSwitch = 2, // Positive limit switch + index pulse
PositiveHomeSwitch = 3, // Positive home switch + index (reverse while the switch is active)
PositiveHomeSwitchNeg = 4, // Positive home switch + index (go positive while the switch is inactive)
NegativeHomeSwitch = 5, // Negative home switch + index (reverse while the switch is active)
NegativeHomeSwitchPos = 6, // Negative home switch + index (reverse while the switch is inactive)
HomeSwitchPositiveIndex = 7, // Home switch + index (start positive, bounce off the positive limit)
HomeSwitchPositiveActiveIndex = 8, // Home switch + index (start positive, reverse while the switch is already active)
HomeSwitchPositiveOvershootIndex = 9, // Home switch + index (start positive, reverse after passing the switch and look for the index)
HomeSwitchPositiveEdgeIndex = 10, // Home switch + index (start positive, reverse after the switch edge)
HomeSwitchNegativeIndex = 11, // Home switch + index (start negative, bounce off the negative limit)
HomeSwitchNegativeActiveIndex = 12, // Home switch + index (start negative, reverse while the switch is already active)
HomeSwitchNegativeOvershootIndex = 13, // Home switch + index (start negative, forward after passing the switch and look for the index)
HomeSwitchNegativeEdgeIndex = 14, // Home switch + index (start negative, forward after the switch edge)
NegativeLimitIndex = 17, // Negative limit switch (no index pulse used)
PositiveLimitIndex = 18, // Positive limit switch (no index pulse used)
PositiveHomeSwitchNoIndex = 19, // Positive home switch (reverse while the switch is active, no index)
PositiveHomeSwitchPosNoIndex = 20, // Positive home switch (go positive while the switch is inactive, no index)
NegativeHomeSwitchNoIndex = 21, // Negative home switch (reverse while the switch is active, no index)
NegativeHomeSwitchNegNoIndex = 22, // Negative home switch (reverse while the switch is inactive, no index)
HomeSwitchPositiveStartNoIndex = 23, // Home switch (start positive, bounce off the positive limit, no index)
HomeSwitchPositiveActiveNoIndex = 24, // Home switch (start positive, reverse while the switch is already active, no index)
HomeSwitchPositiveOvershootNoIndex = 25, // Home switch (start positive, reverse after passing the switch, no index)
HomeSwitchPositiveEdgeNoIndex = 26, // Home switch (start positive, reverse after the switch edge, no index)
HomeSwitchNegativeStartNoIndex = 27, // Home switch (start negative, bounce off the negative limit, no index)
HomeSwitchNegativeActiveNoIndex = 28, // Home switch (start negative, reverse while the switch is already active, no index)
HomeSwitchNegativeOvershootNoIndex = 29, // Home switch (start negative, forward after passing the switch, no index)
HomeSwitchNegativeEdgeNoIndex = 30, // Home switch (start negative, forward after the switch edge, no index)
NegativeIndex = 33, // Index pulse only (find the nearest Z in the negative direction)
PositiveIndex = 34, // Index pulse only (find the nearest Z in the positive direction)
CurrentPosition = 35, // Current position is home (deprecated in CiA 402-2, kept for compatibility)
CurrentPosition37 = 37, // Current position is home (CiA 402-2 replacement for Method 35)
TouchProbe = 37, // Legacy name alias; it is actually Method 37 current position, not Touch Probe
};
Fast motion control
void MoveAbsolute(int32_t position) const; // Absolute positioning (= NewSetpoint(position, false))
void MoveRelative(int32_t distance) const; // Relative positioning (= NewSetpoint(distance, true))
bool StartMotion() const; // Start the motion (enable, = Enable())
void StopMotion() const; // Stop the motion (disable operation, = DisableOperation())
void EmergencyStop() const; // Emergency stop (= QuickStop())
bool IsMoving() const; // Whether in motion (= !TargetReached())
bool IsInPosition() const; // Whether in position (= TargetReached())
bool IsFaulted() const; // Whether a fault exists (= HasFault())
uint16_t GetFaultCode() const; // Fault code (0x603F); a failed read returns the 0xFFFF sentinel, see "option codes and error codes" below
bool ClearFault() const; // Clear the fault (same implementation as FaultReset, written in two phases; true = both writes succeeded)
Option codes and error codes
Option codes (QuickStopOptionCode, 0x605A) and the fault code (GetFaultCode, 0x603F) return a sentinel value on a failed read, with the same convention as the underlying C direct-read entry points, in three tiers by return shape:
| Constant | Value | Description |
|---|---|---|
| READ_FAIL_SENTINEL_I16 | -32768 | signed 16-bit option code (0x605A-0x605E) read failed |
| READ_FAIL_SENTINEL_U16 | 0xFFFF | unsigned 16-bit ErrorCode (0x603F) read failed |
| READ_FAIL_SENTINEL_INT | -1 | read failure of a counting interface that returns int (fail-closed) |
None of the three tiers is a legal value (legal option codes are small values including 0; the error code 0x0000 means no error), so do not treat them as real numbers. Test with is_read_fail_sentinel(v), whose three overloads take int16_t / uint16_t / int by return shape:
bool is_read_fail_sentinel(int16_t v); // Test READ_FAIL_SENTINEL_I16
bool is_read_fail_sentinel(uint16_t v); // Test READ_FAIL_SENTINEL_U16
bool is_read_fail_sentinel(int v); // Test READ_FAIL_SENTINEL_INT
The remaining numeric getters still fall back to 0 on a failed read.
int8 method numbers (0x60E3 list items, -128..-1 are vendor-specific methods) are real values, not sentinels; do not test them with is_read_fail_sentinel.
ReadErrorCode()
uint16_t ReadErrorCode(CiA402SentinelCause* out_cause = nullptr) const;
When you need to tell "real value / read failed / entry missing" apart, use this entry point to read the 0x603F fault code, with the sentinel cause filled in through out_cause. Only a return of 0x0000 means no fault; when the SDK is not ready it returns 0xFFFF and sets the cause to entry missing (fail-closed; a not-ready state is not read as 0 = no fault).
Parameters:
out_cause— may benullptr; when non-null it is filled with the three-state cause
Returns:
uint16_t— the raw0x603Fvalue. When you get the0xFFFFsentinel, useout_causeto judge the cause; do not treat it as a real error code
Related structure:
enum class CiA402SentinelCause : uint8_t {
Value = 0, // The return value is the truth value
ReadFail = 1, // The entry is bound and the runtime returned the 0xFFFF read-failure sentinel
EntryMissing = 2 // The entry is not bound, fall back to 0xFFFF
};
Example:
CiA402SentinelCause cause = CiA402SentinelCause::Value;
uint16_t code = cia.ReadErrorCode(&cause);
if (code == 0xFFFF && cause != CiA402SentinelCause::Value)
printf("故障码不可用 (读失败或入口缺失)\n"); // Fault code unavailable (read failed or entry missing)
Drive support query
SupportedDriveModes()
uint32_t SupportedDriveModes() const;
Supported operation mode bitmask (0x6502, read-only). Bit0=PP, Bit1=VL, Bit2=PV, Bit3=PT, Bit5=HM, Bit6=IP, Bit7=CSP, Bit8=CSV, Bit9=CST, Bit10=CSTCA. A failed read falls back to 0.
GetSupportedModes()
std::vector<ModeCiA402> GetSupportedModes() const;
Get the list of all operation modes the drive supports (each mode is judged from the 0x6502 bit).
SupportedHomingMethods()
std::vector<int8_t> SupportedHomingMethods() const;
Read the list of homing method numbers the drive supports (0x60E3:00 is the count, 0x60E3:01..N are the method numbers), where -128..-1 are vendor-specific methods.
Returns:
std::vector<int8_t>— homing method number list. Failure (SDO timeout / communication error / other abort), a truly empty set (0x60E3:00 = 0, the slave really returns 0 entries) and not supported (no 0x60E3 / 0x60E3:00, abort 0x06020000 / 0x06090011) all collapse into the same shape (an empty vector). An empty vector must not be read as supporting 0 homing methods; subitems that cannot be read are skipped, and no item 0 is fabricated.
TrySupportedHomingMethods()
CiA402ReadResult<std::vector<int8_t>> TrySupportedHomingMethods() const;
Same as above, but the real value / read failed / not supported three states are distinguishable. If any subitem fails to read, the whole result reports that status truthfully (taking the status and abort_code of the first failed subitem), and value must not be used as a real value.
An empty vector with Ok() is not a failure: it means the device really returned 0 methods — an empty set is a genuine value.
To distinguish read failures you do not need a parameter-specific Try variant: on the PDO path look at the data source state (whether the PDO offset hits), on the SDO path look at the abort in the CoE read details. The general escape hatch is TryReadObject<T>(index, subindex); an empty vector from SupportedHomingMethods() must not be read as supporting 0.
Observable read-only result carrier (the return type of TryReadObject<T>() / TrySupportedHomingMethods()):
enum class CiA402ReadStatus : uint8_t {
NotAttempted = 0, // Not attempted yet
Success = 1, // The truth value read (an empty list = the slave really returned 0 entries, which is also the truth)
NotSupported = 2, // The slave has no such object / subindex (abort 0x06020000 / 0x06090011)
ReadFailed = 3 // Timeout / communication error / other abort
};
template<typename T>
struct CiA402ReadResult {
T value{}; // Meaningful only when status == Success
CiA402ReadStatus status;
uint32_t abort_code; // SDO Abort Code (0 on success)
bool Ok() const; // status == Success
bool NotSupported() const; // status == NotSupported
};
template<typename T>
CiA402ReadResult<T> TryReadObject(uint16_t index, uint8_t subindex = 0) const;
Example:
auto r = cia.TrySupportedHomingMethods();
if (r.Ok()) {
if (r.value.empty())
printf("从站确认不支持任何回零方法\n"); // An empty list really returns 0 entries, which is the truth
else
printf("支持 %d 种回零方法\n", (int)r.value.size()); // Supports %d homing methods
} else if (r.NotSupported()) {
printf("从站不支持 0x60E3\n"); // Slave does not support 0x60E3
} else {
printf("读取失败, abort=0x%08X\n", r.abort_code); // Read failed, abort=0x%08X
}
TryGetErrorHistory()
CiA402ReadResult<std::vector<uint32_t>> TryGetErrorHistory(int maxCount = 32) const;
Reads the 0x1003 Pre-defined Error Field: 0x1003:00 is the entry count (u8) and 0x1003:01..N are the error codes, returned as u32 (the low 16 bits carry the valid error code).
CiA402ReadResult<T> carries value + status + abort_code and offers Ok() / NotSupported(). The three states are mutually exclusive and distinguishable:
Success+ empty vector — the device really has 0 history entries. This is a genuine value, not a failure.NotSupported— the 0x1003 object or subindex does not exist (abort 0x06020000 / 0x06090011 / 0x06090012).ReadFailed— the count entry or any item entry failed to read (timeout / communication error / other abort). The cause is the first failing entry, and the count entry takes precedence over the items.
A failed item is never fabricated as a 0 entry: it is skipped, and value must not be used as truth while the status is not Success.
maxCount is the maximum number of entries to read: when the history is longer, only the first maxCount entries are read, and the unread tail is not a failure. maxCount <= 0 is an invalid request: no bus access happens and the result is ReadFailed directly (it is not disguised as "empty history").
The call is read-only: it never writes 0x1003:00. Clearing the history is a separate write to that subindex and is not part of this entry point.
Parameters:
maxCount(int) — maximum number of history entries to read, default 32
Returns:
CiA402ReadResult<std::vector<uint32_t>>—valueis a genuine value only whenOk(); unreadable items are skipped andvaluemust not be used as truth in that case
Example:
auto r = cia.TryGetErrorHistory();
if (r.Ok()) {
if (r.value.empty())
printf("从站真返回 0 条错误历史\n"); // Empty = the truth value, not a failure
else
for (uint32_t code : r.value)
printf("历史错误码: 0x%04X\n", code & 0xFFFF); // Low 16 bits valid
} else if (r.NotSupported()) {
printf("从站不支持 0x1003\n"); // Slave does not support 0x1003
} else {
printf("读取失败, abort=0x%08X\n", r.abort_code); // Do not treat a failure as error code 0
}
TryRead* three-state read-only entry points
The entry points below exist specifically to separate "real value / not supported by the slave / read failed" and return the CiA402ReadResult<T> defined above: only when Ok() (status == Success) is value a real value; NotSupported() means the slave has no such object or subindex; everything else is a read failure (timeout / communication error / other abort; see abort_code). They all perform a single SDO read attempt and have no side effects such as writing the object dictionary, writing PDO or changing the state machine.
| Category | Method | Type or return type | Read/write | Description |
|---|---|---|---|---|
| Three-state read | TryReadOperationModeDisplay() | CiA402ReadResult<ModeCiA402> | read-only | Reads the 0x6061 operation mode display. Forces an SDO read attempt (does not take PDO), to distinguish "the slave really returns a mode" from "read failed / not supported"; for high-rate real-time reads still use OperationMode() |
| Three-state read | TryReadSupportedDriveModes() | CiA402ReadResult<uint32_t> | read-only | Reads the 0x6502 supported mode bitmask. When the value is always 0, use status to tell whether the slave really returned 0 or an SDO read failure / not supported was swallowed into 0 |
| Three-state read | TryReadErrorCode() | CiA402ReadResult<uint16_t> | read-only | Reads the current error code from 0x603F. The three states only go as far as the SDO layer (real value / not supported / read failed) and do not include the "entry missing" cause; to attribute the 0xFFFF sentinel use ReadErrorCode() |
| Three-state read | TryReadStatusword() | CiA402ReadResult<uint16_t> | read-only | Reads the 0x6041 status word (SDO path). For high-rate real-time reads use Statusword() |
| Three-state read | TryReadTorqueActual() | CiA402ReadResult<int16_t> | read-only | Reads the actual torque from 0x6077, in thousandths of the rated torque |
| Three-state read | TryReadDigitalInputs() | CiA402ReadResult<uint32_t> | read-only | Reads the 0x60FD digital input bitmap |
| Three-state read | TryReadDriveData(uint8_t subindex) | CiA402ReadResult<uint32_t> | read-only | Reads vendor-specific drive data by subindex (0x6510, RECORD); the subindex meaning is defined by the slave ESI. Only a read-only getter is provided, never a write |
| Three-state read | TryGetErrorHistory(int maxCount = 32) | CiA402ReadResult<std::vector<uint32_t>> | read-only | Reads the 0x1003 pre-defined error history: Ok() + an empty vector = the device really returns 0 entries (a genuine value); NotSupported = no 0x1003; ReadFailed = the count entry or any item failed to read (the first failing entry is taken). Read-only, does not clear the history |
| Supportability | SupportedDriveModesReadable() | bool | read-only | Tries 0x6502 once: true = the read succeeded; false = not supported or read failed (the two are indistinguishable; to tell them apart use TryReadSupportedDriveModes()) |
PDO offset management
For use in PDO modes such as CSP/CSV/CST to cache the byte offset of each CiA 402 object in the PDO data area (both the struct fields mapped to the real-time process image and the whole-frame snapshots of CopyInputFrame / WriteOutputFrame address through the same set of offsets):
auto& cia = master.GetSlave(1).GetCiA402();
// Initialise the PDO offset cache (called once in SafeOp/OP)
cia.InitializePdoOffsets();
// Check whether it is initialised
if (cia.PdoInitialized()) {
printf("PDO 偏移已初始化\n"); // PDO offsets initialized
}
// Reset the offset cache
cia.ResetPdoOffsets();
Standard object index constants (CiA402Obj)
Can be used together with coe.SDORead / SDOWrite:
| Constant | Value | Description |
|---|---|---|
| CONTROLWORD | 0x6040 | Control word |
| STATUSWORD | 0x6041 | Status word |
| MODES_OF_OPERATION | 0x6060 | Operation mode setting |
| MODES_OF_OPERATION_DISPLAY | 0x6061 | Operation mode display |
| TARGET_POSITION | 0x607A | Target position |
| POSITION_ACTUAL | 0x6064 | Actual position |
| TARGET_VELOCITY | 0x60FF | Target velocity |
| VELOCITY_ACTUAL | 0x606C | Actual velocity |
| TARGET_TORQUE | 0x6071 | Target torque |
| TORQUE_ACTUAL | 0x6077 | Actual torque |
| MAX_TORQUE | 0x6072 | Maximum torque |
| MOTOR_RATED_TORQUE | 0x6076 | Motor rated torque |
| HOME_OFFSET | 0x607C | Homing offset |
| SOFTWARE_POSITION_LIMIT | 0x607D | Software position limit |
| POLARITY | 0x607E | Polarity |
| MAX_PROFILE_VELOCITY | 0x6080 | Maximum profile velocity |
| PROFILE_VELOCITY | 0x6081 | Profile velocity |
| PROFILE_ACCELERATION | 0x6083 | Profile acceleration |
| PROFILE_DECELERATION | 0x6084 | Profile deceleration |
| QUICK_STOP_DECELERATION | 0x6085 | Quick stop deceleration |
| MOTION_PROFILE_TYPE | 0x6086 | Motion profile type |
| HOMING_METHOD | 0x6098 | Homing method |
| SUPPORTED_HOMING_METHODS | 0x60E3 | List of supported homing methods |
| HOMING_SPEEDS | 0x6099 | Homing speeds |
| HOMING_ACCELERATION | 0x609A | Homing acceleration |
| POSITION_OFFSET | 0x60B0 | Position offset (CSP) |
| VELOCITY_OFFSET | 0x60B1 | Velocity offset (CSV) |
| TORQUE_OFFSET | 0x60B2 | Torque offset |
| POSITIVE_TORQUE_LIMIT | 0x60E0 | Positive torque limit |
| NEGATIVE_TORQUE_LIMIT | 0x60E1 | Negative torque limit |
| TOUCH_PROBE_FUNCTION | 0x60B8 | Touch Probe function control |
| TOUCH_PROBE_STATUS | 0x60B9 | Touch Probe status |
| TOUCH_PROBE_POS_EDGE | 0x60BA | Touch Probe positive edge position |
| TOUCH_PROBE_NEG_EDGE | 0x60BB | Touch Probe negative edge position |
| INTERPOLATION_TIME | 0x60C2 | Interpolation time period |
| QUICK_STOP_OPTION | 0x605A | Quick stop option code |
| SHUTDOWN_OPTION | 0x605B | Shutdown option code |
| DISABLE_OPERATION_OPTION | 0x605C | Disable operation option code |
| HALT_OPTION | 0x605D | Halt option code |
| FAULT_REACTION_OPTION | 0x605E | Fault reaction option code |
| DIGITAL_INPUTS | 0x60FD | Digital inputs |
| DIGITAL_OUTPUTS | 0x60FE | Digital outputs |
| TXPDO_DATA_INVALID | 0x603E | TxPDO data validity |
| ERROR_CODE | 0x603F | Error code |
| SUPPORTED_DRIVE_MODES | 0x6502 | Supported modes bitmap |
| SYNCHRONIZATION_SETTINGS | 0x60D9 | Synchronization settings |
| DRIVE_SYNC_STATUS | 0x60DA | Drive synchronization status (read-only) |
| DRIVE_DATA | 0x6510 | Vendor-specific drive data (RECORD, read-only) |
Control word command constants
| Constant | Value | Description |
|---|---|---|
| CW_SHUTDOWN | 0x06 | Shutdown command |
| CW_SWITCH_ON | 0x07 | Switch on command |
| CW_ENABLE_OPERATION | 0x0F | Enable operation |
| CW_DISABLE_VOLTAGE | 0x00 | Disable voltage |
| CW_QUICK_STOP | 0x02 | Quick stop |
| CW_FAULT_RESET | 0x80 | Fault reset |
| CW_HALT | 0x0100 (Bit 8) | Halt |
Status word bitmask constants
CiA402Obj defines the following status word bitmask constants (only these 7; for the state machine base bits Bit0-6 use ParseState() / StateDrive(), the SDK does not export separate constants such as SW_READY_TO_SWITCH_ON):
| Constant | Value | Description |
|---|---|---|
| SW_FAULT | 0x0008(Bit 3) | Fault |
| SW_WARNING | 0x0080(Bit 7) | Warning |
| SW_REMOTE | 0x0200(Bit 9) | Remote mode |
| SW_TARGET_REACHED | 0x0400(Bit 10) | Target reached |
| SW_INTERNAL_LIMIT | 0x0800(Bit 11) | Internal limit active |
| SW_HOMING_ATTAINED | 0x1000(Bit 12) | Homing attained |
| SW_HOMING_ERROR | 0x2000(Bit 13) | Homing error |
Full example
CSP mode — cyclic synchronous position control
#include "ethercat.hpp"
using namespace darra::ethercat;
int main() {
darra::ethercat::dll_t dll;
EtherCATMaster master(dll);
if (!master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build())
return 1;
auto& cia = master.GetSlave(1).GetCiA402();
cia.OperationMode(ModeCiA402::CSP);
cia.InitializePdoOffsets();
if (!master.SetState(EcState::OP) || !master.Start())
return 1;
if (!cia.Enable()) {
printf("使能失败, 当前状态: %d\n", static_cast<int>(cia.StateDrive())); // Enable failed, current state: %d
return -1;
}
// The PDO cycle callback sends the target position (registered with SetPDOCallbackSync)
int32_t nextPosition = cia.PositionActual(); // Trajectory start = current position, no jump
master.Events().SetPDOCallbackSync([&](uint16_t /*mi*/) {
if (cia.HasFault())
return; // Hand the fault to a background thread: FaultReset() contains a 1 ms delay and must not run in the real-time callback
// The callback only reads/writes mapped fields (no SDO, no Sleep). In CSP the control word stays at 0x000F
cia.TargetPosition(nextPosition);
});
getchar();
cia.Disable();
master.Stop();
return 0;
}