Skip to main content

CiA 402 — Servo drive helpers

CiA 402 (IEC 61800-7-204) is a servo drive device protocol built on CoE. CiA402Instance wraps drive state machine management, operation mode switching and motion parameter access.

CiA 402 runs on top of CoE (SDO). CiA402Instance must be constructed separately (CiA402Instance::new(...)); it is not a chained accessor method on the slave object.

CSP / synchronized axis hard rules
  • Cyclic synchronous position mode is fixed at 0x6060 = 8; under CSP do not write 0x001F (bit4 is the PP/HM NewSetpoint).
  • Use (status_word & 0x6F) for state checks: == 0x27 = OperationEnabled; to detect a fault use (status_word & 0x4F) == 0x08 (0x4F only looks at faults and cannot be used to judge the operating state).
  • While not enabled, during a handshake and during a group stop, the target position always equals the actual position, to avoid jumps.
  • Fault reset sends 0x80 (bit7 rising edge) in the OP process data; when the SDK wraps it as two phases it completes over two cycles as 0x0006 → 0x0086; do not Sleep inside the PDO callback.
  • Issue each axis in turn from the same PDO callback (on_pdo_cyclic_sync); do not start a thread per axis.
  • The 0x1F of single-axis PP must not be copied to CSP / synchronized axes; synchronized axes use CSP + DC only.

Two usage styles: slave.cia402_* vs CiA402Instance​

The SDK provides two CiA 402 interfaces; choose by scenario:

slave.cia402_* — lightweight direct calls (SDO-only)​

Convenience methods attached to Slave that do not depend on the PDO mapping and go entirely over SDO. Suited to one-off operations / debugging / non-cyclic scenarios.

Available methods:

  • slave.cia402_state() → CiA402State — read the current drive state
  • slave.cia402_enable() → Result<()> — one-call enable (advances the state machine over SDO)
  • slave.cia402_set_mode(mode: i8) → Result<()> / slave.cia402_mode() → i8 — operation mode read/write (0x6060 / 0x6061)
  • slave.cia402_status_word() → u16 — read 0x6041
  • slave.cia402_write_control_word(cw: u16) → Result<()> — write 0x6040
  • slave.cia402_fault_reset() → Result<()> — reset 0x6040 bit 7

Example:

let slave = master.slave(1);

// debugging: check after power-up whether the drive is in OperationEnabled
println!("当前状态: {:?}", slave.cia402_state()); // Current state: {:?}

// one-call enable + read state
slave.cia402_enable()?;
println!("使能后状态字: 0x{:04X}", slave.cia402_status_word()); // Status word after enable: 0x{:04X}

CiA402Instance — full high-performance interface (PDO + SDO)​

The PDO mapping must be scanned first with Cia402PdoMap::scan(), then the full instance is constructed. Objects already mapped in 0x1C12 / 0x1C13 go through whole-frame PDO copy/write; objects not in the mapping fall back to SDO automatically. Suited to cyclic motion control / high-frequency read/write.

Typical scenarios:

  • Frequent reads of ActualPosition / ActualVelocity / StatusWord within the PDO cycle
  • Writes of TargetPosition / ControlWord within the cycle, over PDO without blocking
  • High-level state machine wrappers such as enable() / quick_stop() / fault_reset()

Choosing between them​

  • Debugging / offline diagnostics / one-off operations → use slave.cia402_*; no PDO mapping scan is needed and the interface is simple
  • Cyclic motion control / real-time data streaming → use CiA402Instance, which goes through whole-frame PDO copy/write
  • Mixed: enable at startup with slave.cia402_enable(), then switch to CiA402Instance for cyclic control after entering OP (the two can coexist on the same slave)
The two state enums are not interchangeable

The SDK contains two separate CiA 402 state enums: their values mean the same thing but they are different types and cannot be compared with each other:

  • slave.cia402_state() returns darra_ethercat::CiA402State (#[repr(i32)], variants NotReady / FaultReaction / ...)
  • CiA402Instance::state_drive() returns darra_ethercat::slave::StateCiA402 (#[repr(u8)], variants NotReadyToSwitchOn / FaultReactionActive / ...)

The variant names differ between the two (NotReady vs NotReadyToSwitchOn, FaultReaction vs FaultReactionActive). Always compare with the same enum the corresponding method returns, for example slave.cia402_state() == CiA402State::OperationEnabled or drv.state_drive() == StateCiA402::OperationEnabled; do not mix the two.

Construction​

A CiA 402 instance must first scan the PDO mapping table, then be constructed separately:

use darra_ethercat::{Cia402PdoMap, CiA402Instance};

// 1. scan the PDO mapping (read 0x1C12/0x1C13)
let pdo_map = Cia402PdoMap::scan(master.index(), 1)?;

// 2. create the CiA 402 instance
let drv = CiA402Instance::new(master.index(), 1, pdo_map);

PDO mapping scan​

Cia402PdoMap::scan()​

pub fn scan(master_index: u16, slave_index: u16) -> Result<Self>

Scans the slave PDO mapping, reads the mapping parameters of the 0x1C12/0x1C13 object series and builds a complete mapping cache.

Once the mapping is built, CiA402Instance reads and writes go through whole-frame PDO copy/write first; objects not in the mapping fall back to SDO automatically.

Example:

let pdo_map = Cia402PdoMap::scan(master.index(), 1)?;

// inspect the mapping information
for entry in pdo_map.output_entries() {
println!("RxPDO: 0x{:04X}:{:02X} {}bit @offset {}",
entry.od_index, entry.sub_index, entry.bit_length, entry.byte_offset);
}
for entry in pdo_map.input_entries() {
println!("TxPDO: 0x{:04X}:{:02X} {}bit @offset {}",
entry.od_index, entry.sub_index, entry.bit_length, entry.byte_offset);
}

State control​

enable() advances to OperationEnabled in one call (it internally completes the full state chain + fault reset + QuickStop recovery + 0x605A option code check); disable / disable_operation / quick_stop / fault_reset write the Controlword once and return immediately; check the result with state_drive().

enable(max_retries) / enable_default()​

pub fn enable(&self, max_retries: i32) -> Result<StateCiA402>
pub fn enable_default(&self) -> Result<StateCiA402> // equivalent to enable(10)

Enables the drive: internally it completes the full SwitchOnDisabled → ReadyToSwitchOn → SwitchedOn → OperationEnabled sequence, the fault reset and the QuickStop recovery per CiA 402-2.

Parameters:

  • max_retries — maximum number of retries

Returns:

  • Ok(StateCiA402) — returns Ok(StateCiA402::OperationEnabled) only on reaching OperationEnabled
  • Err(_) — enable timed out / the current state refuses enabling / max_retries is invalid; the failure reason is in the DarraError::CiA402Failed text and can be re-checked with state_drive()

Example:

// one-call enable (completes the full state machine internally)
match drv.enable_default() {
Ok(_) => drv.set_target_position(next_position), // Ok means OperationEnabled
Err(e) => println!("使能失败: {}, 当前状态: {:?}", e, drv.state_drive()), // Enable failed: {}, current state: {:?}
}

disable()​

pub fn disable(&self) -> Result<()>

Disables the servo (-> SwitchOnDisabled); power is fully removed. Returns Err if the Controlword write fails.

disable_operation()​

pub fn disable_operation(&self) -> Result<()>

Disables operation (OperationEnabled -> SwitchedOn). Returns Err if the Controlword write fails.

quick_stop()​

pub fn quick_stop(&self) -> Result<()>

Quick stop. Returns Err if the Controlword write fails.

fault_reset()​

pub fn fault_reset(&self) -> Result<()>

Clears the fault (writes Shutdown first, then FaultReset|Shutdown). Returns Err if either Controlword write fails.

transition_command()​

pub fn transition_command(current: StateCiA402, target: StateCiA402) -> Result<u16>

Associated function (takes no &self): from the state transition table it works out the Controlword to send in one step from current to target, and only computes it, it does not send anything. Useful when your own state machine wants to compute first and send later, or to take the value ahead of time inside the PDO cycle.

  • Ok(u16) — the Controlword for that single-step transition; when current == target it returns the control word that holds the current state
  • Err(_) — illegal transition (for example SwitchOnDisabled → OperationEnabled takes several steps and the table has no such edge)
// Compute without sending: take the SwitchedOn -> OperationEnabled control word
let cw = CiA402Instance::transition_command(
StateCiA402::SwitchedOn, StateCiA402::OperationEnabled)?;

request_transition()​

pub fn request_transition(&self, target: StateCiA402) -> Result<()>

Reads the current state (0x6041) → works out the Controlword from the transition table → writes 0x6040. It advances exactly one step and does not wait for the state to actually arrive; to advance further, call it again every cycle and re-read the state.

  • Ok(()) — the Controlword has been written (this does not mean the drive has finished the transition)
  • Err(_) — reading the current state failed / the transition is illegal / writing the Controlword failed

step_enable()​

pub fn step_enable(&self) -> Result<StateCiA402>

A single-step advance of the enable state machine and the lower-level primitive behind enable(); it writes the Controlword at most once per call:

  • Already in OperationEnabled — returns Ok(OperationEnabled) directly without writing the Controlword
  • In NotReadyToSwitchOn — returns Ok(NotReadyToSwitchOn) without writing the Controlword (waiting for the drive to reach SwitchOnDisabled by itself)
  • Fault / FaultReactionActive / Unknown — returns Err; a fault state is not treated as enablement
  • Any other state — sends the control word from next_enable_controlword() and returns Ok(下发前读到的状态)
The return value is the state read before the command is sent

Ok carries the state before this step, not the state after the transition. To confirm enablement you have to call state_drive() again; enable() decides success only because the next loop iteration reads OperationEnabled.

fault_reset_step()​

pub fn fault_reset_step(&self, step: i32) -> bool

The two-phase primitive for a fault reset; it produces the bit7 rising edge across two cycles (do not write twice inside one cycle, and do not Sleep inside the PDO callback):

stepControlword writtenEffect
00x0006Low phase, bit7=0 and bit2=1 (Quick Stop is not triggered)
10x0086High phase, bit7=1 produces the rising edge
  • step accepts only 0 / 1; any other value returns false
  • It works only when 0x6040 is mapped as process data and the slave is in OP; in SafeOp / PreOp / when not mapped it always returns false and never degrades into a mailbox write
  • true = that phase was written successfully; false = illegal argument / operating condition not met / write failed

State readback​

state_drive()​

pub fn state_drive(&self) -> StateCiA402

Parses the current drive state from the StatusWord.

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateCiA402 {
NotReadyToSwitchOn = 0, // initializing
SwitchOnDisabled = 1, // drive disabled
ReadyToSwitchOn = 2, // ready
SwitchedOn = 3, // switched on
OperationEnabled = 4, // operation enabled
QuickStopActive = 5, // quick stop
FaultReactionActive = 6, // fault reaction active
Fault = 7, // fault
Unknown = 99, // unknown state
}

StateCiA402 methods and the state transition table​

pub fn from_statusword(sw: u16) -> Self
pub fn hold_controlword(self) -> Result<u16>
pub fn next_enable_controlword(self) -> Result<u16>
pub fn command_to(self, target: Self) -> Result<u16>
  • from_statusword(sw) — associated function: parses the state out of the status word; when it fits no standard state it returns Unknown and does not panic
  • hold_controlword() — the control word to send to hold the current state
  • next_enable_controlword() — the next control word on the enable chain; for an enabled / initializing / fault-class / unknown state it cannot advance the enable in one step and returns Err
  • command_to(target) — the single-step transition control word; when self == target it is the same as hold_controlword(); a combination the table does not contain returns Err

Holding control word hold_controlword():

Current stateControlwordConstant
SwitchOnDisabled / NotReadyToSwitchOn0x0000CW_DISABLE_VOLTAGE
ReadyToSwitchOn0x0006CW_SHUTDOWN
SwitchedOn0x0007CW_SWITCH_ON
OperationEnabled0x000FCW_ENABLE_OPERATION
QuickStopActive0x0002CW_QUICK_STOP
Fault / FaultReactionActivereturns Errcannot be left by holding a control word; an explicit FaultReset is required
Unknownreturns Erran unknown state has no holding control word

Next enable step next_enable_controlword():

Current stateControlword
SwitchOnDisabled0x0006 (CW_SHUTDOWN)
ReadyToSwitchOn0x0007 (CW_SWITCH_ON)
SwitchedOn0x000F (CW_ENABLE_OPERATION)
QuickStopActive0x0000 (CW_DISABLE_VOLTAGE)
OperationEnabled / NotReadyToSwitchOn / Fault / FaultReactionActive / Unknownreturns Err

Single-step transition command_to() (matches the implementation item by item):

Current state → target stateControlword
SwitchOnDisabled → ReadyToSwitchOn0x0006 (CW_SHUTDOWN)
ReadyToSwitchOn → SwitchedOn0x0007 (CW_SWITCH_ON)
SwitchedOn → OperationEnabled0x000F (CW_ENABLE_OPERATION)
ReadyToSwitchOn → OperationEnabled0x000F (CW_ENABLE_OPERATION)
OperationEnabled → SwitchedOn0x0007 (CW_SWITCH_ON)
OperationEnabled → ReadyToSwitchOn0x0006 (CW_SHUTDOWN)
SwitchedOn → ReadyToSwitchOn0x0006 (CW_SHUTDOWN)
ReadyToSwitchOn → SwitchOnDisabled0x0000 (CW_DISABLE_VOLTAGE)
OperationEnabled → SwitchOnDisabled0x0000 (CW_DISABLE_VOLTAGE)
SwitchedOn → SwitchOnDisabled0x0000 (CW_DISABLE_VOLTAGE)
QuickStopActive → SwitchOnDisabled0x0000 (CW_DISABLE_VOLTAGE)
OperationEnabled → QuickStopActive0x0002 (CW_QUICK_STOP)
Fault → SwitchOnDisabled0x0086 (CW_FAULT_RESET | CW_SHUTDOWN)
QuickStopActive → OperationEnabled0x000F (CW_ENABLE_OPERATION)
Any other combination (including Fault → Fault, any → Unknown, Unknown → *)returns Err

statusword() / controlword()​

pub fn statusword(&self) -> u16
pub fn controlword(&self) -> u16
pub fn set_controlword(&self, value: u16)

Related methods:

  • target_reached() -> bool — target reached (Bit 10)
  • has_fault() -> bool — fault present (Bit 3)
  • has_warning() -> bool — warning present (Bit 7)
  • is_remote() -> bool — remote mode (Bit 9)

Operation modes​

operation_mode() / set_operation_mode()​

pub fn operation_mode(&self) -> i8
pub fn set_operation_mode(&self, mode: ModeCiA402)
#[repr(i8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModeCiA402 {
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 with commutation angle mode
}

is_mode_supported()​

pub fn is_mode_supported(&self, mode: ModeCiA402) -> bool

Checks whether the drive supports the specified operation mode (determined through 0x6502 SupportedDriveModes).

ModeCiA402::supported_bit()​

pub fn supported_bit(&self) -> Option<u32>

Returns the bit number of that operation mode in the 0x6502 bitmask, for building a mask or testing the bit yourself:

ModeBit number
PP0
VL1
PV2
PT3
HM5
IP6
CSP7
CSV8
CST9
CSTCA10

The current implementation returns Some(bit) for every variant; the caller takes the value out of Some and then tests the bit against supported_drive_modes() with & (1 << bit). Bit number 4 corresponds to no ModeCiA402 variant (that bit is reserved in 0x6502).

let masks = drv.supported_drive_modes();
if let Some(bit) = ModeCiA402::CSP.supported_bit() {
println!("CSP 位号 {}, 本机支持: {}", bit, (masks >> bit) & 1 != 0); // CSP bit number {}, supported on this unit: {}
}

Motion parameters​

CategoryMethodTypeRead/writeDescription
Positionposition_actual()i32read-onlyActual position (0x6064)
Velocityvelocity_actual()i32read-onlyActual velocity (0x606C)
Torquetorque_actual()i16read-onlyActual torque (0x6077)
Positiontarget_position() / set_target_position()i32read/writeTarget position (0x607A)
Velocitytarget_velocity() / set_target_velocity()i32read/writeTarget velocity (0x60FF)
Torquetarget_torque() / set_target_torque()i16read/writeTarget torque (0x6071)

Profile parameters​

CategoryMethodTypeRead/writeDescription
Profileprofile_velocity() / set_profile_velocity()u32read/writeProfile velocity (0x6081)
profile_acceleration() / set_profile_acceleration()u32read/writeProfile acceleration (0x6083)
profile_deceleration() / set_profile_deceleration()u32read/writeProfile deceleration (0x6084)
Stopquick_stop_deceleration() / set_quick_stop_deceleration()u32read/writeQuick stop deceleration (0x6085)

Polarity and profile configuration​

CategoryMethodTypeRead/writeDescription
Configurationpolarity() / set_polarity()u8read/writePolarity (0x607E)
Configurationmotion_profile_type() / set_motion_profile_type()i16read/writeMotion profile type (0x6086)
Option codequick_stop_option_code() / set_quick_stop_option_code()i16read/writeQuick stop option (0x605A, OD/SDO path). A failed read collapses to 0 and cannot be distinguished from a genuine 0; quick_stop_option_native() on the same object uses the read-failure sentinel convention

Option codes (0x605A–0x605E)​

Five drive option codes that determine the deceleration/stop behavior of each state transition, accessed through low-level direct read/write. Each is an i16 read/write.

CategoryMethodTypeRead/writeDescription
Option codequick_stop_option_native() / set_quick_stop_option_native()i16read/writeQuick stop option code (0x605A). 0 = immediate cut-off, 1 = ramp deceleration, 2 = Quick Stop deceleration, 3 = torque stop; 5/6/7/8 = hold QuickStopActive after deceleration (allows direct T16 → OperationEnabled)
shutdown_option() / set_shutdown_option()i16read/writeShutdown option code (0x605B): deceleration behavior on OperationEnabled → ReadyToSwitchOn
disable_operation_option() / set_disable_operation_option()i16read/writeDisable Operation option code (0x605C): behavior on OperationEnabled → SwitchedOn
halt_option() / set_halt_option()i16read/writeHalt option code (0x605D): CW Bit8 Halt behavior (1 = profile ramp, 2 = QS deceleration, 3 = torque stop)
fault_reaction_option() / set_fault_reaction_option()i16read/writeFault Reaction option code (0x605E): behavior after fault detection (-1 = vendor, 0 = immediate cut-off, 1/2/3 = deceleration)

Return values and the read-failure sentinel: normal = the real value; on a failed read a sentinel that cannot occur is returned instead of a real reading (the valid option codes in this section are small values including 0). Do not use it as a real number; test it with the predicate functions. Rust has no overloading, so the read-failure sentinel has three tiers by return shape, and the predicates are likewise split into three functions with matching suffixes:

  • Signed 16-bit option code (0x605A–0x605E) read (i16): a failed read returns the sentinel (a negative value, not a valid reading)
  • Unsigned 16-bit drive_error_code (0x603F) read (u16): a failed read returns the sentinel (not a valid reading)
  • Counting-style read interfaces that return int (error_history / supported_homing_methods_native and so on) (i32): a failed read returns the sentinel as a whole (a negative value, fail-closed)

Predicate functions (pick the one matching the return shape):

  • is_read_fail_sentinel_i16(v) (bool) — tests for the i16 read-failure sentinel
  • is_read_fail_sentinel_u16(v) (bool) — tests for the u16 read-failure sentinel
  • is_read_fail_sentinel_int(v) (bool) — tests for the int read-failure sentinel
i8 method numbers (0x60E3 list entries; -128..-1 are vendor-specific methods) are real values and are not sentinels; do not test them with is_read_fail_sentinel_int.
quick_stop_option_native() (0x605A) and quick_stop_option_code() (0x605A) in "Polarity and profile configuration" above point to the same object. The read-failure sentinel convention applies to the read side of the five methods in this table.

Example:

// hold QuickStopActive (5) after a quick stop so operation can be resumed directly
drv.set_quick_stop_option_native(5);

// use ramp deceleration (2) for the fault reaction instead of an immediate cut-off
drv.set_fault_reaction_option(2);

// read an option code: a failed read returns the sentinel (not a valid value); handle it as a failure
let qs = drv.quick_stop_option_native();
if is_read_fail_sentinel_i16(qs) {
println!("QuickStopOption 读取失败, 按失败处理"); // Failed to read QuickStopOption, treated as a failure
}

Error code and error history​

CategoryMethodTypeRead/writeDescription
Errordrive_error_code()u16read-onlyCurrent Error Code (0x603F, CiA 402 annex). Normal = the real value; a failed read returns the sentinel, not a valid value (0x0000 means no error); do not use it as a real number, test it with is_read_fail_sentinel_u16(v)
Error historyerror_history()Vec<u32>read-onlyReads the Pre-defined Error Field (0x1003) and returns the drive's internal persistent error history (low 16 bits of the Error Code). A failed read returns the sentinel as a whole (fail-closed) and the SDK maps it to an empty Vec; the caller must handle it as a failure (an empty Vec does not confirm that there is no history)
try_error_history(max_count)Cia402ReadResult<Vec<u32>>read-onlyThree-state observable read of 0x1003: Success + empty Vec = the slave really returned 0 entries; NotSupported = 0x1003 does not exist; ReadFailed = read failed. Any failed entry makes the whole call fail; a 0 error code is never fabricated
clear_error_history()boolread/writeClears the drive's internal error history (0x1003:00 = 0)

Reading try_error_history(max_count):

  • status == Success → value is the real value: an empty Vec means the slave really returned 0 entries, and status separates it from a read failure.
  • status == NotSupported → 0x1003 does not exist (SDO abort 0x06020000 / 0x06090011 and similar).
  • status == ReadFailed → read failed: the count entry (0x1003:00) or any entry (0x1003:01..N) could not be read, so value is empty and is not a real value. No 0 error code is fabricated and no partial history is handed back.
  • status == NotAttempted → max_count == 0: not a single bus request is made, and no conclusion is claimed.
  • If the slave reports more entries than max_count, the result is truncated to max_count; that is not a failure.

This is the same three-state carrier Cia402ReadResult<T> as try_supported_homing_methods() (the 0x60E3 homing method list): real value / read failed / not supported are separated by status, and an empty collection is a real value only when Success.

Example:

// current error code (a failed read returns the sentinel, not a real error code)
let ec = drv.drive_error_code();
if is_read_fail_sentinel_u16(ec) {
println!("Error Code 读取失败, 按失败处理"); // Failed to read Error Code, treated as a failure
}

// error history: the folded form (a failed read also yields an empty Vec; an empty Vec does not confirm no history)
let history = drv.error_history();

// three-state observable form: an empty history and a failed read are distinguishable
let r = drv.try_error_history(32);
match r.status {
Cia402ReadStatus::Success if r.value.is_empty() =>
println!("从站真返回 0 条错误历史"), // Slave actually returned 0 error-history entries
Cia402ReadStatus::Success =>
println!("错误历史: {:08X?}", r.value), // Error history: {:08X?}
Cia402ReadStatus::NotSupported =>
println!("从站不支持 0x1003"), // Slave does not support 0x1003
Cia402ReadStatus::NotAttempted =>
println!("max_count == 0,未读总线"), // max_count == 0, the bus was not read
Cia402ReadStatus::ReadFailed =>
println!("读取失败: abort=0x{:08X}", r.abort_code), // Read failed: abort=0x{:08X}
}

Touch probe​

CategoryMethodTypeRead/writeDescription
Touch probeconfigure_touch_probe(function: u16)-write-onlyConfigure the probe function (0x60B8)
touch_probe_status()u16read-onlyProbe status (0x60B9)
touch_probe_positive_edge()i32read-onlyPositive-edge captured position (0x60BA)
touch_probe_negative_edge()i32read-onlyNegative-edge captured position (0x60BB)

Digital IO​

CategoryMethodTypeRead/writeDescription
Inputdigital_inputs()u32read-onlyDigital inputs (0x60FD), 32-bit bitmap
Outputdigital_outputs() / set_digital_outputs()u32read/writeDigital outputs (0x60FE:01), 32-bit bitmap

Example:

// read the digital inputs
let inputs = drv.digital_inputs();
let limit_switch = (inputs & 0x01) != 0; // bit 0

// set the digital outputs
drv.set_digital_outputs(0x03); // output bits 0 and 1

Software position limits​

CategoryMethodTypeRead/writeDescription
Limitssoftware_position_limit_min() / set_software_position_limit_min()i32read/writeSoftware position limit lower bound (0x607D:01)
software_position_limit_max() / set_software_position_limit_max()i32read/writeSoftware position limit upper bound (0x607D:02)

Example:

// set the motion range limits
drv.set_software_position_limit_min(-1_000_000);
drv.set_software_position_limit_max(1_000_000);

Extended motion parameters​

CategoryMethodTypeRead/writeDescription
Torquemax_torque() / set_max_torque()u16read/writeMaximum torque (0x6072), thousandths of rated
motor_rated_torque() / set_motor_rated_torque()u32read/writeMotor rated torque (0x6076), mNm
Offsetsposition_offset() / set_position_offset()i32read/writePosition offset (0x60B0), added in CSP mode
velocity_offset() / set_velocity_offset()i32read/writeVelocity offset (0x60B1), added in CSV mode
torque_offset() / set_torque_offset()i16read/writeTorque offset (0x60B2)
Interpolationinterpolation_time_period_value() / set_interpolation_time_period_value()u8read/writeInterpolation time period value (0x60C2:01)
interpolation_time_period_index() / set_interpolation_time_period_index()i8read/writeInterpolation time period index (0x60C2:02), period = Value × 10^Index seconds

Torque limits​

CategoryMethodTypeRead/writeDescription
Torquepositive_torque_limit() / set_positive_torque_limit()u16read/writePositive torque limit (0x60E0), thousandths of rated
negative_torque_limit() / set_negative_torque_limit()u16read/writeNegative torque limit (0x60E1), thousandths of rated

Homing speeds and acceleration​

CategoryMethodTypeRead/writeDescription
Hominghoming_speed_search() / set_homing_speed_search()u32read/writeHoming speed for the search (0x6099:01), fast search for the reference signal
homing_speed_zero() / set_homing_speed_zero()u32read/writeHoming speed for zero (0x6099:02), slow precise positioning at the zero point
homing_acceleration() / set_homing_acceleration()u32read/writeHoming acceleration (0x609A)

Example:

drv.set_operation_mode(ModeCiA402::HM);
drv.set_homing_method(1);

// set the homing speeds and acceleration
drv.set_homing_speed_search(5000); // search speed
drv.set_homing_speed_zero(500); // zero speed
drv.set_homing_acceleration(10000); // homing acceleration

Fast motion control​

new_setpoint()​

pub fn new_setpoint(&self, position: i32, relative: bool)

Sends a new positioning command in PP mode. Sets the target position and triggers Controlword Bit 4 (New Setpoint).

Parameters:

  • position -- target position
  • relative -- true = relative positioning, false = absolute positioning

Example:

drv.set_operation_mode(ModeCiA402::PP);
drv.set_profile_velocity(10000);
drv.set_profile_acceleration(50000);

// in the PDO callback: enable first, then send the positioning command
if drv.state_drive() == StateCiA402::OperationEnabled {
drv.new_setpoint(100000, false); // absolute positioning to 100000
// drv.new_setpoint(5000, true); // or a relative move by 5000
}

clear_new_setpoint()​

pub fn clear_new_setpoint(&self)

Clears the NewSetpoint flag in PP mode (Controlword Bit4=0). Call it after target_reached() to complete the SetPointAck handshake.

Example:

if drv.target_reached() {
drv.clear_new_setpoint();
}

start_homing()​

pub fn start_homing(&self)

Starts homing in HM mode. set_homing_method() must be set first.

Related methods:

  • homing_method() / set_homing_method() (i8) -- homing method (0x6098)
  • home_offset() / set_home_offset() (i32) -- home offset (0x607C)
  • homing_attained() (bool) -- homing attained (Bit 12)
  • homing_error() (bool) -- homing error (Bit 13)

Example:

drv.set_operation_mode(ModeCiA402::HM);
drv.set_homing_method(35); // homing on the current position

// in the PDO callback:
if drv.state_drive() == StateCiA402::OperationEnabled {
drv.start_homing();
// check drv.homing_attained() / drv.homing_error() in later cycles
}

is_standard_homing_method()​

pub fn is_standard_homing_method(method: i8) -> bool

Associated function: tells whether a homing method number falls inside the ETG.6010 standard range; use it together with the value read back by homing_method().

  • 1..=35 or 37 — true, a standard homing method
  • -128..=-1 — false, a vendor-specific method (still a legal number, it just is not a standard method)
  • 0 — false, meaning no homing method has been selected

Example:

let method = drv.homing_method();
if method == 0 {
println!("尚未选择回零方法"); // No homing method selected yet
} else if CiA402Instance::is_standard_homing_method(method) {
println!("标准回零方法 {} (0x6098)", method); // Standard homing method {} (0x6098)
} else {
println!("厂商自定义回零方法 {}", method); // Vendor-defined homing method {}
}

Drive information​

supported_drive_modes()​

pub fn supported_drive_modes(&self) -> u32

Supported drive modes bitmask (0x6502). Bit 0=PP, Bit 1=VL, Bit 2=PV, Bit 3=PT, Bit 5=HM, Bit 6=IP, Bit 7=CSP, Bit 8=CSV, Bit 9=CST.

supported_homing_methods()​

pub fn supported_homing_methods(&self) -> Vec<i8>

Reads the list of supported homing method numbers reported by the slave (0x60E3).

Parameters:

  • None

Returns:

  • Vec<i8> — list of homing method numbers (0x60E3 list entries). An empty Vec corresponds to all three of the following cases at once and must not be read as only one of them

What each of the three cases returns:

  • Failure (SDO timeout / communication exception / other abort) — returns an empty Vec
  • Empty set (SI0=0 and the read succeeded; the slave genuinely returns 0 entries) — returns an empty Vec
  • Not supported (the slave has no 0x60E3 or no 0x60E3:00; SDO abort 0x06020000 object does not exist / 0x06090011 subindex does not exist) — returns an empty Vec
An empty Vec must not be read as 「supports 0 homing methods」

This wrapper folds the three cases above into one shape (an empty Vec), so an empty Vec may be a genuine failure, a genuine 0-entry return from the slave, or the slave not supporting 0x60E3 at all. A failed read returns the sentinel as a whole and is handled as a failure (fail-closed), which is distinguishable from 「genuinely returns 0 entries」 (that is distinguishable there). A dedicated entry point try_supported_homing_methods() now exists; the try_read_* convenience methods still do not cover 0x60E3. Use that dedicated entry point when the three states must be distinguished; try_read_object() in the "Observable read-only" section of this page remains the generic route (read the entry count 0x60E3:00 separately, whose status truthfully distinguishes a successful read / not supported / read failure, and on success a value of 0 means it genuinely returns 0 entries; then read 0x60E3:01..n one by one by entry count to get the method numbers — this is a separate read path).

Example:

let methods = drv.supported_homing_methods();
// an empty Vec = failure / empty set / not supported; do not take it as "supports 0 homing methods"
if methods.is_empty() {
println!("未能确认支持的回零方法 (失败 / 空集 / 不支持)"); // Could not confirm the supported homing methods (read failed / empty set / not supported)
} else {
println!("支持的回零方法: {:?}", methods); // Supported homing methods: {:?}
}

try_supported_homing_methods()​

pub fn try_supported_homing_methods(&self) -> Cia402ReadResult<Vec<i8>>

Reads the list of supported homing method numbers reported by the slave (0x60E3); the three states of real value / read failure / not supported are distinguishable. Uses the same carrier Cia402ReadResult<T> as try_read_error_code().

Parameters:

  • None

Returns:

  • Cia402ReadResult<Vec<i8>> — homing method number list with status; read it from the status / value / abort_code fields together

What each of the three cases returns:

  • Real value (status == Success) — the complete list is in value; an empty Vec = the slave genuinely returns 0 homing methods (it truly supports no homing method); this is a real value, not a failure
  • Read failure (status == ReadFailed, SDO timeout / communication exception / other abort) — value is meaningless (empty Vec)
  • Not supported (status == NotSupported, the 0x60E3 object/subindex does not exist, SDO abort 0x06020000 / 0x06090011 / 0x06090012) — value is meaningless (empty Vec)
note

A failed subentry read must never fabricate entries: if even one subentry could not be read, report that status truthfully for the whole result (taking the status and abort code of the first failed subentry); value must not be used as a real value, and a failure must never be pushed into the list as method 0. abort_code carries the SDO Abort Code as usual (0 on success). Method numbers are i8; -128..-1 are vendor-specific methods, which are real values and not sentinels — do not filter them with the read-failure sentinel predicates.

note

The older entry points supported_homing_methods() / supported_homing_methods_native() fold "failure / genuinely empty set / not supported" into one shape (an empty Vec), and a failure also yields an empty Vec; use try_supported_homing_methods() when they must be distinguishable. The older entry points "skip, do not fabricate entries" for subentries that cannot be read.

Example:

let r = drv.try_supported_homing_methods();
match r.status {
Cia402ReadStatus::Success if r.value.is_empty() =>
println!("从站确认不支持任何回零方法"), // The slave confirms it supports no homing method
Cia402ReadStatus::Success =>
println!("支持的回零方法: {:?}", r.value), // Supported homing methods: {:?}
Cia402ReadStatus::NotSupported =>
println!("从站不支持 0x60E3"), // Slave does not support 0x60E3
_ => println!("读取失败: abort=0x{:08X}", r.abort_code), // Read failed: abort=0x{:08X}
}

supported_homing_methods_native()​

pub fn supported_homing_methods_native(&self) -> Vec<i8>

Reads the list of supported homing method numbers reported by the slave (0x60E3, low-level direct read).

Parameters:

  • None

Returns:

  • Vec<i8> — list of homing method numbers (0x60E3 list entries). An empty Vec corresponds to all three of the following cases at once and must not be read as only one of them

What each of the three cases returns:

  • Failure (SDO timeout / communication exception / other abort) — returns an empty Vec
  • Empty set (SI0=0 and the read succeeded; the slave genuinely returns 0 entries) — returns an empty Vec
  • Not supported (the slave has no 0x60E3 or no 0x60E3:00; SDO abort 0x06020000 object does not exist / 0x06090011 subindex does not exist) — returns an empty Vec, in the same tier as failure
An empty Vec does not mean it is confirmed that no homing method is supported

This wrapper folds the three cases above into one shape (an empty Vec); all three are in the same tier. A failed read returns the sentinel as a whole and is handled as a failure (fail-closed), which is distinguishable from 「genuinely returns 0 entries」 (that is distinguishable there); for how to tell them apart see the explanation under supported_homing_methods() above. Use try_supported_homing_methods() when they must be distinguishable.

Example:

let methods = drv.supported_homing_methods_native();
// an empty Vec = failure / empty set / not supported; do not take it as "supports 0 homing methods"
if methods.is_empty() {
println!("未能确认支持的回零方法 (失败 / 空集 / 不支持)"); // Could not confirm the supported homing methods (read failed / empty set / not supported)
} else {
println!("支持的回零方法: {:?}", methods); // Supported homing methods: {:?}
}

Observable read-only (distinguishing real value / not supported / failure)​

A normal getter (such as statusword() / operation_mode()) falls back to the default value 0 when the SDO read fails, so the caller cannot tell "the slave genuinely returns 0" from "the read failed and was swallowed into 0". Exception: the option code getters (quick_stop_option_native() / shutdown_option() / disable_operation_option() / halt_option() / fault_reaction_option()) and drive_error_code() return a sentinel value on a failed read (not a valid value and not a real reading) instead of swallowing it into 0; see the 「Option codes (0x605A–0x605E)」 and 「Error code and error history」 sections of this page. The try_read_* series performs one genuine SDO read-only attempt and truthfully distinguishes three states from the SDO Abort Code: read succeeded (real value) / not supported by the slave / read failed. Strictly read-only, with no side effects of any kind: no object dictionary writes, no PDO writes, no state machine changes.

When to use
  • Debugging / device capability probing: determine whether the slave really supports an optional object (such as 0x6502 / 0x60FD).
  • For high-frequency real-time reads keep using the normal getters (statusword() / position_actual() and so on, PDO-first with zero overhead); try_read_* forces SDO and is not suitable for cyclic calls.

Cia402ReadStatus​

Read status enum that distinguishes "a real value from a successful read" from "read failure / not supported by the slave".

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cia402ReadStatus {
NotAttempted = 0, // not attempted yet
Success = 1, // read succeeded; the value is the slave's real value
NotSupported = 2, // the slave does not support this object (SDO abort 0x06020000 / 0x06090011)
ReadFailed = 3, // SDO read failed (timeout / communication exception / other abort)
}

Related methods:

  • classify_abort(abort_code: u32) (Cia402ReadStatus) — classifies an SDO Abort Code as NotSupported / ReadFailed
  • description() (&'static str) — Chinese description of the status (implements Display)

Cia402ReadResult<T>​

Read result with status. The caller uses status to distinguish a real value / not supported / failure; value is only trustworthy when status == Success.

#[derive(Debug, Clone, Copy)]
pub struct Cia402ReadResult<T> {
pub value: T, // the value read (meaningful only on Success)
pub status: Cia402ReadStatus, // read status
pub abort_code: u32, // SDO Abort Code (0 = no abort)
}

Related methods:

  • ok() (bool) — whether the read succeeded and the value is trustworthy (status == Success)
  • not_supported() (bool) — whether the slave does not support the object (status == NotSupported)

try_read_object<T>()​

pub fn try_read_object<T: Cia402Readable>(&self, index: u16, subindex: u8) -> Cia402ReadResult<T>

Performs one observable SDO read-only attempt on any CiA 402 object. T must implement Cia402Readable (already provided for u8/i8/u16/i16/u32/i32/u64/i64). When fewer bytes are available, the value is zero-extended to the available width.

Example:

let r = drv.try_read_object::<u32>(0x6502, 0);
match r.status {
Cia402ReadStatus::Success => println!("支持模式位掩码: 0x{:08X}", r.value), // Supported mode bit mask: 0x{:08X}
Cia402ReadStatus::NotSupported => println!("从站不支持 0x6502"), // Slave does not support 0x6502
_ => println!("读取失败: abort=0x{:08X}", r.abort_code), // Read failed: abort=0x{:08X}
}

Convenience read-only methods​

Wrappers for commonly used read-only objects; all return Cia402ReadResult<T> and are purely read-only:

  • try_read_statusword() (Cia402ReadResult<u16>) — status word (0x6041). For high-frequency real-time reads use statusword()
  • try_read_error_code() (Cia402ReadResult<u16>) — error code (0x603F); the three states real value / not supported / failure are distinguished. drive_error_code() uses the read-failure sentinel convention (test with is_read_fail_sentinel_u16)
  • try_read_supported_drive_modes() (Cia402ReadResult<u32>) — supported drive modes bitmask (0x6502)
  • try_read_digital_inputs() (Cia402ReadResult<u32>) — digital inputs (0x60FD)
  • try_read_operation_mode_display() (Cia402ReadResult<i8>) — operation mode display (0x6061)
  • try_read_drive_data(subindex: u8) (Cia402ReadResult<u32>) — vendor-specific drive data (0x6510, RECORD)
  • try_read_position_actual() (Cia402ReadResult<i32>) — actual position (0x6064)
  • try_read_torque_actual() (Cia402ReadResult<i16>) — actual torque (0x6077), thousandths of rated

supported_drive_modes_readable()​

pub fn supported_drive_modes_readable(&self) -> bool

Whether the slave really supports the 0x6502 (Supported Drive Modes) object. true = the read succeeded; false = not supported or the read failed (use try_read_supported_drive_modes().status to distinguish the reason further).

Example:

if drv.supported_drive_modes_readable() {
let modes = drv.try_read_supported_drive_modes().value;
println!("支持的驱动模式: 0x{:08X}", modes); // Supported drive modes: 0x{:08X}
} else {
println!("从站不支持 0x6502 或读取失败"); // Slave does not support 0x6502, or the read failed
}

TxPDO data validity​

txpdo_data_invalid()​

pub fn txpdo_data_invalid(&self) -> bool

Whether the TxPDO data is invalid (0x603E). Non-zero means the drive's TxPDO data is untrustworthy (for example, the position value is meaningless while the encoder is not ready).

if !drv.txpdo_data_invalid() {
let pos = drv.position_actual(); // the data is valid
}

Synchronization​

CategoryMethodTypeRead/writeDescription
Synchronizationsynchronization_settings() / set_synchronization_settings()u16read/writeSynchronization settings (0x60D9:01)
drive_sync_status()u16read-onlyDrive synchronization status (0x60DA)

Complete examples​

CSP mode — cyclic synchronous position control​

use darra_ethercat::{Cia402PdoMap, CiA402Instance, ModeCiA402, StateCiA402};

let pdo_map = Cia402PdoMap::scan(master.index(), 1)?;
let drv = CiA402Instance::new(master.index(), 1, pdo_map);

// set the operation mode
drv.set_operation_mode(ModeCiA402::CSP);

// one-call enable (completes the full state machine internally)
match drv.enable_default() {
Ok(_) => { /* reached OperationEnabled, continue */ }
Err(err) => {
println!("使能失败: {}, 当前状态: {:?}", err, drv.state_drive()); // Enable failed: {}, current state: {:?}
return Ok(());
}
}

// issue the target every cycle in the PDO callback
let events = master.events();
events.on_pdo_cyclic_sync(move |_master_idx| {
drv.set_target_position(calculate_next_position());
});

PP mode — profile position control​

use darra_ethercat::{Cia402PdoMap, CiA402Instance, ModeCiA402};
use std::sync::atomic::{AtomicBool, Ordering};

let pdo_map = Cia402PdoMap::scan(master.index(), 1)?;
let drv = CiA402Instance::new(master.index(), 1, pdo_map);

drv.set_operation_mode(ModeCiA402::PP);
drv.set_profile_velocity(10000);
drv.set_profile_acceleration(50000);
drv.set_profile_deceleration(50000);

// one-call enable
match drv.enable_default() {
Ok(_) => { /* reached OperationEnabled, continue */ }
Err(err) => {
println!("使能失败: {}, 当前状态: {:?}", err, drv.state_drive()); // Enable failed: {}, current state: {:?}
return Ok(());
}
}

// send the positioning command
drv.new_setpoint(100000, false); // absolute positioning

// clear the flag in the PDO callback once the target is reached
let homing_done = AtomicBool::new(false);
let events = master.events();
events.on_pdo_cyclic_sync(move |_| {
if !homing_done.load(Ordering::Relaxed) && drv.target_reached() {
drv.clear_new_setpoint();
homing_done.store(true, Ordering::Relaxed);
}
});

HM mode — homing​

use darra_ethercat::{Cia402PdoMap, CiA402Instance, ModeCiA402};

let pdo_map = Cia402PdoMap::scan(master.index(), 1)?;
let drv = CiA402Instance::new(master.index(), 1, pdo_map);

drv.set_operation_mode(ModeCiA402::HM);
drv.set_homing_method(35); // homing on the current position
drv.set_homing_speed_search(5000);
drv.set_homing_speed_zero(500);
drv.set_homing_acceleration(10000);

// one-call enable
match drv.enable_default() {
Ok(_) => { /* reached OperationEnabled, continue */ }
Err(err) => {
println!("使能失败: {}, 当前状态: {:?}", err, drv.state_drive()); // Enable failed: {}, current state: {:?}
return Ok(());
}
}

// start homing
drv.start_homing();

let events = master.events();
events.on_pdo_cyclic_sync(move |_| {
if drv.homing_attained() {
println!("回零完成"); // Homing complete
}
if drv.homing_error() {
println!("回零错误"); // Homing error
}
});

Parameter validation​

let drv = CiA402Instance::new(master.index(), 1, pdo_map);

// check whether the profile parameters meet the PP/PV mode requirements
let warnings = drv.validate_profile_parameters(Some(1)); // PP mode
for w in &warnings {
println!("警告: {}", w); // Warning: {}
}

Standard object index constants​

Can be used with slave.sdo_read/sdo_write:

ConstantValueDescription
OD_CONTROLWORD0x6040Control word
OD_STATUSWORD0x6041Status word
OD_MODES_OF_OPERATION0x6060Operation mode setting
OD_MODES_OF_OPERATION_DISPLAY0x6061Operation mode display
OD_TARGET_POSITION0x607ATarget position
OD_POSITION_ACTUAL0x6064Actual position
OD_TARGET_VELOCITY0x60FFTarget velocity
OD_VELOCITY_ACTUAL0x606CActual velocity
OD_TARGET_TORQUE0x6071Target torque
OD_TORQUE_ACTUAL0x6077Actual torque
OD_PROFILE_VELOCITY0x6081Profile velocity
OD_PROFILE_ACCELERATION0x6083Profile acceleration
OD_PROFILE_DECELERATION0x6084Profile deceleration
OD_MAX_TORQUE0x6072Maximum torque
OD_MOTOR_RATED_TORQUE0x6076Motor rated torque
OD_HOME_OFFSET0x607CHome offset
OD_SOFTWARE_POSITION_LIMIT0x607DSoftware position limit
OD_POLARITY0x607EPolarity
OD_MAX_PROFILE_VELOCITY0x6080Maximum profile velocity
OD_MOTION_PROFILE_TYPE0x6086Motion profile type
OD_HOMING_METHOD0x6098Homing method
OD_HOMING_SPEEDS0x6099Homing speeds
OD_HOMING_ACCELERATION0x609AHoming acceleration
OD_POSITION_OFFSET0x60B0Position offset (CSP)
OD_VELOCITY_OFFSET0x60B1Velocity offset (CSV)
OD_TORQUE_OFFSET0x60B2Torque offset
OD_TOUCH_PROBE_FUNCTION0x60B8Touch probe function control
OD_TOUCH_PROBE_STATUS0x60B9Touch probe status
OD_TOUCH_PROBE_POS_EDGE0x60BATouch probe positive-edge position
OD_TOUCH_PROBE_NEG_EDGE0x60BBTouch probe negative-edge position
OD_INTERPOLATION_TIME_PERIOD0x60C2Interpolation time period
OD_DIGITAL_INPUTS0x60FDDigital inputs
OD_DIGITAL_OUTPUTS0x60FEDigital outputs
OD_QUICK_STOP_OPTION_CODE0x605AQuick stop option code
OD_QUICK_STOP_DECELERATION0x6085Quick stop deceleration
OD_SUPPORTED_DRIVE_MODES0x6502Supported drive modes bitmask
OD_ERROR_CODE0x603FError code
OD_DRIVE_DATA0x6510Vendor-specific drive data (RECORD, read-only)

Control word command constants​

ConstantValueDescription
CW_SHUTDOWN0x06Shutdown command
CW_SWITCH_ON0x07Switch on command
CW_ENABLE_OPERATION0x0FEnable operation
CW_DISABLE_VOLTAGE0x00Disable voltage
CW_QUICK_STOP0x02Quick stop
CW_FAULT_RESET0x80Fault reset
CW_HALT0x0100Halt bit (Bit 8, pauses motion without disabling)

Status word bitmask constants​

ConstantValueDescription
SW_READY_TO_SWITCH_ON0x0001 (Bit 0)Ready to switch on
SW_SWITCHED_ON0x0002 (Bit 1)Switched on
SW_OPERATION_ENABLED0x0004 (Bit 2)Operation enabled
SW_FAULT0x0008 (Bit 3)Fault
SW_VOLTAGE_ENABLED0x0010 (Bit 4)Voltage enabled
SW_QUICK_STOP0x0020 (Bit 5)Quick stop
SW_SWITCH_ON_DISABLED0x0040 (Bit 6)Switch on disabled
SW_WARNING0x0080 (Bit 7)Warning
SW_REMOTE0x0200 (Bit 9)Remote mode
SW_TARGET_REACHED0x0400 (Bit 10)Target reached
SW_INTERNAL_LIMIT0x0800 (Bit 11)Internal limit active
SW_OP_MODE_SPECIFIC_10x1000 (Bit 12)Mode-specific bit 1
SW_OP_MODE_SPECIFIC_20x2000 (Bit 13)Mode-specific bit 2