Configuration
Get a MasterConfig& reference through master.GetConfig() to read and change the master communication configuration. Every configuration property uses the C++ property-style overloads (same-name getter/setter).
Getting the configuration object
auto& config = master.GetConfig();
Properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Cycle configuration | LoopCycle() | uint32_t | Read/write | PDO exchange cycle (nanoseconds). The real-time driver's RT thread sends and receives PDO frames at this cycle; minimum 31 µs (= 31,000 ns, whole microseconds, the specification floor) |
| HighResolutionTimer() | bool | Read/write | Read: whether the system clock resolution is already 1ms (or finer); write: turn it on or off for this process, effective immediately. The installer leaves it off | |
| Network transmission | FrameHighPriority() | bool | Read/write | High frame priority (off by default). Raises the frame send priority at the OS level. Linux: SO_PRIORITY; Windows: thread priority boost |
| UseUdp() | bool | Read/write | UDP frame mode (only for EtherCAT gateway / EAP devices; standard ESC slaves do not support it). Encapsulates datagrams in UDP/IP for transmission | |
| IsUdpAvailable() | bool | Read-only | Whether UDP mode is available. Reflects whether the UDP socket was created successfully during system initialization | |
| VlanId() | uint16_t | Read/write | VLAN ID (IEEE 802.1Q, 0-4095, 0 = disabled). Takes effect in real-time driver mode only | |
| VlanPriority() | uint8_t | Read/write | VLAN priority PCP (0-7, 7 = highest). Requires VlanId > 0 and real-time driver mode | |
| PDO configuration | OverlappingGroups() | bool | Read/write | PDO overlapping mode (off by default). In the LRW frame the inputs overwrite the output positions; only for special slaves such as TI ESC |
| PackedMode() | bool | Read/write | Packed PDO mapping mode (disabled by default). When enabled, PDO variables are packed bit by bit without forcing byte alignment; suits bit-level IO modules | |
| FilterThreshold() | uint32_t | Read/write | Consecutive PDO frame loss threshold (default 3). The callback fires only when the number of consecutive lost frames reaches this value | |
| Mutex protection | MutexProtection() | bool | Read/write | Mutex protection (enabled by default). When enabled it locks automatically to keep access thread-safe; when disabled you manage thread safety yourself |
| Adaptive timeout | AdaptiveTimeoutEnabled() | bool | Read/write | Adaptive timeout (enabled by default). Samples the network RTT automatically and computes the best PDO timeout dynamically |
| State transition timeouts | TimeoutInitToPreOp() | int | Read/write | INIT→PREOP timeout (milliseconds), default 0. 0 = use the default 3000ms |
| TimeoutPreOpToSafeOp() | int | Read/write | PREOP→SAFEOP timeout (milliseconds), default 0. 0 = use the default 10000ms | |
| TimeoutSafeOpToOp() | int | Read/write | SAFEOP→OP timeout (milliseconds), default 0. 0 = use the default 10000ms | |
| Watchdog | PdiWatchdogMs() | int | Read/write | PDI watchdog timeout (milliseconds), default 0. 0 = use the slave default |
| ProcessDataWatchdogMs() | uint32_t | Read/write | Process data watchdog timeout (milliseconds), default 0. 0 = use the slave default | |
| Scan configuration | ScanRevisionMatch() | ScanRevisionMatchMode | Read/write | Revision matching policy for scanned slaves (default IgnoreRevision) |
| Frame repeat | FrameRepeatCount() | uint8_t | Read/write | Frame repeat count (ETG.1500 5.4.3, default 1 = disabled, range 1-3). A global setting; it applies only to groups in which every slave supports it |
| DC configuration | DriftCompensation() | bool | Read/write | DC drift compensation switch (default false) |
Cycle configuration
LoopCycle()
uint32_t LoopCycle() const;
void LoopCycle(uint32_t ns);
PDO exchange cycle time, in nanoseconds (ns).
The master RT thread (the real-time driver timer) sends and receives PDO frames at this cycle. The value sets how often process data is refreshed between master and slaves — smaller values refresh faster but demand more from the system's real-time behaviour. The real-time driver supports a minimum of 31 µs (= 31,000 ns, whole microseconds) — the product's minimum cycle is 31 µs, which is the specification floor.
On Windows stay at or above 125,000ns (125 µs). The real-time driver fully supports the 31 µs specification floor (= 31,000 ns, whole microseconds); smaller values mean nothing on Windows because the application layer cannot write at a higher rate.
Example:
auto& config = master.GetConfig();
config.LoopCycle(1000000); // 1ms = 1,000,000ns
config.LoopCycle(500000); // 500 µs = 500,000ns
config.LoopCycle(250000); // 250 µs = 250,000ns
config.LoopCycle(125000); // 125 µs = 125,000 ns (recommended minimum on Windows)
DC drift compensation is off by default. When you need to keep sync accuracy over long runs, turn it on with DriftCompensation() below.
Mailbox frames ride along in the PDO cycle automatically and use no extra frames.
HighResolutionTimer()
bool HighResolutionTimer() const;
void HighResolutionTimer(bool v);
Read: whether the system clock resolution is already 1ms (or finer); it is not hard-wired to false. Write: turn it on or off for this process, effective immediately. The installer leaves it off, so you set it here in the cycle configuration. With it on, waits are more accurate but the mouse may feel sluggish; PDO on isolated cores does not depend on it. It is a no-op on non-Windows systems.
The read returns whether the system is already at 1ms; it is not hard-wired to false, and the installer does not turn it on.
Example:
config.HighResolutionTimer(true);
Network transmission
FrameHighPriority()
bool FrameHighPriority() const;
void FrameHighPriority(bool v);
Raises the EtherCAT frame send priority at the OS level to reduce queuing delay.
Default: false (off by default)
- Windows — process/thread priority boost
- Linux — the SO_PRIORITY=6 socket option, the system network stack's queuing priority (requires root)
UseUdp()
bool UseUdp() const;
void UseUdp(bool v);
UDP frame mode (ETG.1500 5.3.7). When enabled, EtherCAT datagrams no longer use raw Ethernet frames (EtherType 0x88A4) and are instead carried inside UDP/IP packets (UDP port 34980).
The ESC (EtherCAT Slave Controller) chip of a standard EtherCAT slave works at the data link layer and only recognises raw Ethernet frames with EtherType=0x88A4. Frames wrapped in UDP/IP are invisible to these slaves.
Only applies to:
- EtherCAT gateway or bridge devices that support the UDP protocol
- Communication with EtherCAT Automation Protocol (EAP) devices
Does not apply to: direct connection to standard EtherCAT slaves (EK1100, EL7041, servo drives and so on)
IsUdpAvailable()
bool IsUdpAvailable() const;
Whether the UDP socket was created successfully during system initialization. Only when this method returns true can you switch to UDP mode with UseUdp(true).
In some restricted environments (missing network privileges, a firewall blocking it and so on) the UDP socket may fail to be created; IsUdpAvailable() then returns false and calling UseUdp(true) has no effect.
Example:
if (config.IsUdpAvailable()) {
config.UseUdp(true); // Switch to UDP mode
}
VlanId()
uint16_t VlanId() const;
void VlanId(uint16_t v);
VLAN ID (IEEE 802.1Q, ETG1000_4 Table 9, an optional ETG.1500 feature). Range 0-4095; 0 disables the VLAN tag.
After a non-zero value is set, a 4-byte 802.1Q VLAN tag is inserted into every EtherCAT frame, and the frame header grows from the standard 14 bytes to 18 bytes.
VLAN configuration has to be set before entering SafeOp (after Build succeeds and before SetState(OP)).
The VLAN tag feature only takes effect when the real-time driver is installed. The real-time driver sends raw frames directly, so the VLAN tag is preserved intact on the cable.
VlanPriority()
uint8_t VlanPriority() const;
void VlanPriority(uint8_t v);
VLAN priority (PCP — Priority Code Point, IEEE 802.1Q, an optional ETG.1500 feature). Range 0-7, where 7 is the highest priority. It is encoded in the top 3 bits of the TCI field of the VLAN tag.
VlanId() has to be set to a non-zero value first, and real-time driver mode has to be in use, for this property to mean anything. On QoS-capable switches, frames with a higher PCP value are forwarded first.
Typical VLAN scenarios:
- Converged IT/OT networks — use VLANs to separate industrial control traffic from office network traffic
- TSN (Time-Sensitive Networking) — IEEE 802.1Q priority tags provide QoS scheduling
- Coexisting network segments — one physical network carries several EtherCAT segments
Example:
// Set the VLAN after Build() succeeds (requires the real-time driver mode)
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}");
master.Build();
// Configure the VLAN before entering SafeOp
auto& config = master.GetConfig();
config.VlanId(100);
config.VlanPriority(6); // High priority
PDO configuration
OverlappingGroups()
bool OverlappingGroups() const;
void OverlappingGroups(bool v);
PDO overlapping mode switch. When enabled, the outputs and inputs of each slave share the same logical address range (the larger of the two sizes); the LRW command writes the outputs on the way out, and on the way back the ESC replaces the same positions with the input data, which reduces the frame size.
Default: false (off by default)
It can only be set in the INIT or PRE_OP state, because the memory layout is fixed on entering SAFE_OP.
The overlap happens only at the logical-address level of the frame. The output and input mappings always point at separate memory areas, and every API behaves the same.
Slaves built on the TI (Texas Instruments) EtherCAT Slave Controller must have overlapping mode enabled, otherwise LRW commands do not work correctly. Do not enable it for standard Beckhoff or third-party slaves; some slaves do not support FMMU logical address overlap and will refuse the SAFE_OP transition.
PackedMode()
bool PackedMode() const;
void PackedMode(bool v);
Packed PDO mapping mode switch. When enabled, PDO variables are packed bit by bit without forcing byte alignment.
Default: false (disabled by default, byte-aligned mode)
It can only be set in the INIT or PRE_OP state, because the memory layout is fixed on entering SAFE_OP.
It suits bit-level IO modules (digital IO terminals such as the Beckhoff EL1008/EL2008), whose PDO data is a single bit; enabling PackedMode packs several bit IOs tightly into contiguous memory and saves IOmap space.
Example:
config.PackedMode(true); // Enable tight bit packing
FilterThreshold()
uint32_t FilterThreshold() const;
void FilterThreshold(uint32_t v);
Consecutive PDO frame loss threshold; the default is 3.
The master checks in every PDO cycle whether the frame returned normally. A single lost frame is treated as occasional interference and only counted; the PDOFrameLoss callback fires only when the number of consecutive lost frames reaches this threshold, which avoids a flood of alarms from occasional losses.
Example:
config.FilterThreshold(5); // The callback fires only after 5 consecutive lost frames
PDO configuration works together with slave grouping. Because each group has its own divider and frame loss tracking, frame loss in a high-rate group and in a low-rate group do not affect each other.
Scan configuration
ScanRevisionMatch()
ScanRevisionMatchMode ScanRevisionMatch() const;
void ScanRevisionMatch(ScanRevisionMatchMode v);
Revision matching policy for scanned slaves. It controls how strictly the revision number of a slave found during Build() must match the slave in the DENI configuration.
Default: ScanRevisionMatchMode::IgnoreRevision
Related enum:
enum class ScanRevisionMatchMode : int {
Exact = 0, // Exact match on VendorID + ProductID + RevisionID
CompatibleHigher = 1, // Compatibility match: scanned RevisionID >= configured RevisionID
IgnoreRevision = 2 // Ignore RevisionID, match VendorID + ProductID only (default)
};
Example:
config.ScanRevisionMatch(ScanRevisionMatchMode::CompatibleHigher);
DC configuration
DriftCompensation()
bool DriftCompensation() const;
void DriftCompensation(bool v);
void DriftCompensation(bool v, int32_t thresholdNs, int32_t gain);
DC drift compensation switch. When enabled, the master periodically measures the deviation of the DC system time and writes a compensation value (0x0920).
Default: false
The third overload takes custom parameters:
thresholdNs— drift threshold (nanoseconds), default 1000gain— compensation gain, default 100
Other call forms: master_other::enable_drift_compensation / SlaveDC::EnableDriftCompensation. The free function defaults to a 100ns threshold and a gain of 1, which differs from this property's defaults of 1000 / 100.
Example:
// Use the default parameters
config.DriftCompensation(true);
// Custom parameters
config.DriftCompensation(true, 1000, 512); // threshold=1000 ns, gain=512
Frame repeat
FrameRepeatCount()
uint8_t FrameRepeatCount() const;
void FrameRepeatCount(uint8_t v);
Frame repeat (ETG.1500 5.4.3): a global setting for how many times the same PDO frame is sent per cycle; it applies to eligible groups automatically.
Default: 1 (disabled), range 1-3
This property is a master-level global setting and is filtered per group at runtime — frame repeat is executed only for groups in which every slave declares FrameRepeatSupport=1 in its ESI. Group eligibility is computed automatically during the IO mapping stage:
- every slave in the group supports it → frame repeat is enabled for that group
- any slave in the group does not support it → that group skips frame repeat
ETG.1500 defines frame repeat as a master-level capability with one global repeat count. Because EtherCAT PDO frames are broadcast with LRW, individual slaves cannot be treated differently inside the same frame, so all-or-nothing per group is the only compliant approach. There is no need for a different repeat count per group.
This parameter and each slave's FrameRepeatSupport flag are both included in the DENI configuration file. When a DENI export is loaded on another master, each group's frame repeat eligibility is computed correctly without the ESI files.
Example:
// Global setting: send the same PDO frame 2 times per cycle for every eligible group
config.FrameRepeatCount(2);
Mutex protection
MutexProtection()
bool MutexProtection() const;
void MutexProtection(bool v);
Mutex protection switch. It controls whether PDO reads and writes take a lock automatically to stay thread-safe.
- Enabled (default) — the framework locks automatically, so access is thread-safe
- Disabled — the automatic mutex is off; you manage thread safety yourself and save the lock contention overhead
Default: true
With mutex protection disabled you must keep PDO data thread-safe yourself. This suits scenarios with very tight latency requirements where you can manage concurrency on your own.
Adaptive timeout
AdaptiveTimeoutEnabled()
bool AdaptiveTimeoutEnabled() const;
void AdaptiveTimeoutEnabled(bool v);
Adaptive timeout switch. When enabled, the system samples the network round-trip time (RTT) automatically and computes the best PDO timeout dynamically instead of using a fixed default.
Default: true (enabled by default)
- Enabled (default) — samples the RTT automatically and computes the timeout dynamically, which markedly reduces timeout-induced frame loss
- Off — uses the fixed default timeout value
In most networks a fixed timeout is far larger than the real RTT, so an occasional lost frame waits too long and eats into the following cycle time. Adaptive timeout samples the actual network latency, keeps a safety margin and computes the best timeout value, which markedly reduces timeout-induced frame loss and the cascading frame loss it causes.
State transition timeouts
TimeoutInitToPreOp()
int TimeoutInitToPreOp() const;
void TimeoutInitToPreOp(int v);
INIT→PREOP state transition timeout, in milliseconds (ms).
Default: 0 (uses the system default of 3000ms)
A non-zero value overrides the default timeout. It suits slaves that need longer to initialize (devices with slow firmware loading or EEPROM reads, for example).
Example:
config.TimeoutInitToPreOp(5000); // 5 second timeout
TimeoutPreOpToSafeOp()
int TimeoutPreOpToSafeOp() const;
void TimeoutPreOpToSafeOp(int v);
PREOP→SAFEOP state transition timeout, in milliseconds (ms).
Default: 0 (uses the system default of 10000ms)
This stage includes SM/FMMU configuration and PDO mapping and usually takes the longest. You may need to increase the timeout when there are many slaves or the PDO configuration is complex.
Example:
config.TimeoutPreOpToSafeOp(15000); // 15 second timeout
TimeoutSafeOpToOp()
int TimeoutSafeOpToOp() const;
void TimeoutSafeOpToOp(int v);
SAFEOP→OP state transition timeout, in milliseconds (ms).
Default: 0 (uses the system default of 10000ms)
Example:
config.TimeoutSafeOpToOp(12000); // 12 second timeout
- Many slaves — a large network (>50 slaves) may need a larger PreOp→SafeOp timeout
- Special slaves — some servo drives or safety devices initialize slowly
- Debugging — increase the timeout so you can watch problems in the transition
- Value 0 — uses the system default, which suits most scenarios
Watchdog
PdiWatchdogMs()
int PdiWatchdogMs() const;
void PdiWatchdogMs(int v);
PDI (Process Data Interface) watchdog timeout, in milliseconds (ms).
The PDI watchdog monitors the accesses of the slave's local application (the microcontroller firmware) to the ESC. If the slave firmware does not access the PDI interface within the given time, the ESC raises a watchdog error, which means the slave application may have crashed.
Default: 0 (uses the default in the slave EEPROM/ESI)
Example:
config.PdiWatchdogMs(100); // PDI watchdog 100 ms
The PDI watchdog and the process data watchdog are two independent monitoring mechanisms. The PDI watchdog monitors the slave's internal firmware; the process data watchdog monitors communication from the master.
ProcessDataWatchdogMs()
uint32_t ProcessDataWatchdogMs() const;
void ProcessDataWatchdogMs(uint32_t v);
Process data watchdog timeout, in milliseconds (ms).
The process data watchdog monitors PDO communication from the master to the slave. If the slave receives no valid process data frame within the given time (SyncManager 2/3 is not accessed by the master), the ESC raises a watchdog timeout and the slave may drop from OP to SafeOp by itself.
Default: 0 (uses the default in the slave EEPROM/ESI, usually 100ms)
Example:
config.ProcessDataWatchdogMs(200); // Process data watchdog 200 ms
The process data watchdog timeout should be several times the PDO cycle (LoopCycle) so that it does not fire during normal operation. The recommended value is 10-100 times the PDO cycle. For example, with LoopCycle=1ms set the watchdog to 100-200ms.
IOmap locking
LockIOmap / UnlockIOmap
bool LockIOmap(); // try-lock: true = lock held; false = not acquired, must not enter the critical section
void UnlockIOmap(); // Call only when LockIOmap() returned true
Locks and unlocks the IOmap manually (EtherCATMaster member methods, kept for compatibility with explicit locking), for multi-threaded access to the PDO buffer. With MutexProtection(false) you have to call them yourself in matching pairs.
LockIOmap() is a try-lock and does not block: only a true return means the lock was taken, and the critical section must then end with a matching UnlockIOmap(); on false (another thread holds the lock / the master is not ready / it is shutting down) you must not enter the critical section and must not call UnlockIOmap() either — an unpaired unlock is recorded by the runtime as a cross-thread, repeated or unpaired Unlock error.
For RAII, use darra::ethercat::master_other::IomapLock guard(master); (also a try-lock: the lock is held only when ok() / operator bool is true; if it is not taken, nothing happens and the destructor does not unlock). Do not implement partial / typed updates as lock plus whole-frame write: a whole-frame write is an unconditional replacement that overwrites concurrent writes from other owners, and it is not transactional.
Three thread-safety modes compared:
- Automatic mutex —
MutexProtection(true)(default). General use; thread safety is handled for you - Manual IOmap lock —
MutexProtection(false)+LockIOmap/UnlockIOmap. Use it for multi-threaded access to the PDO buffer; the lock is held only whenLockIOmap()returnstrue, and only then do you unlock in a matching call - No lock —
MutexProtection(false)without calling Lock. Single-threaded writes with no contention
In coordinated multi-axis interpolation, each slave's target position goes through its own versioned partial RMW (PatchOutputFrame: 1748 takes the whole frame plus a token → patch → 1749 commits by token). Atomicity comes from the transaction token, not from the IOmap lock.
Example (multi-axis interpolation: one versioned partial RMW per axis):
// Write the multi-axis positions in the PDO callback (registered with SetPDOCallbackSync)
master.Events().SetPDOCallbackSync([&](uint16_t mi) {
// Partial updates go through the 1748/1749 versioned transactions. Do not change this to
// "LockIOmap + CopyOutputFrame + modify fields + WriteOutputFrame":
// WriteOutputFrame is an unconditional whole-frame replacement: it overwrites concurrent writes from other owners and is not RMW.
if (!darra::SlavePDO::PatchOutputFrame(
dll, master.MasterNumber(), 1, 0, &targetPos1, sizeof(targetPos1))) {
// Transaction refused (out of range / conflicts exhausted / expired): handle it honestly, do not assume the write happened
}
darra::SlavePDO::PatchOutputFrame(
dll, master.MasterNumber(), 2, 0, &targetPos2, sizeof(targetPos2));
darra::SlavePDO::PatchOutputFrame(
dll, master.MasterNumber(), 3, 0, &targetPos3, sizeof(targetPos3));
});
Use LockIOmap() / UnlockIOmap() only when you need to protect multi-threaded access to the PDO buffer yourself (the master_other::IomapLock RAII wrapper is recommended and is also a try-lock); it does not replace the versioned transaction, and partial updates still go through PatchOutputFrame.
Startup parameter snapshot (read-only read / optimistic concurrent replace)
The two entry points live in the header slave/startup.hpp, namespace darra::ethercat::slave_startup, and their arguments are byte-for-byte aligned with ec_startup_param_t: slave_startup::ReadStartupSnapshot / slave_startup::ReplaceStartupSnapshot.
| Category | Method | Type or return type | Read/write | Description |
|---|---|---|---|---|
| Startup snapshot | slave_startup::ReadStartupSnapshot(mi, si, buffer, capacity, required, generation, revision, source_flags) | int | Read-only | Read-only snapshot of the startup parameters; the startup parameter queue is not modified. When capacity is insufficient the runtime never truncates: it returns the real count through required and reports failure, so the caller grows the buffer and reads again and always ends up with a complete snapshot. 0 = success; negative = invalid argument / insufficient capacity / not ready |
| slave_startup::ReplaceStartupSnapshot(mi, si, params, count, expected_generation, expected_revision, new_revision) | int | Write-only | Whole-snapshot replace with optimistic concurrency on (generation, revision): a mismatch with the current snapshot is rejected and nothing is written, so parameters someone else just wrote are never silently overwritten; on success the new revision number is returned through new_revision for use by the next replace. 0 = success; negative = expected values do not match / invalid argument / not ready |
Parameters:
mi/si(uint16_t) — master index / slave index (1-based)buffer(ec_startup_param_t*) — output buffer, byte-for-byte aligned withec_startup_param_t;capacityis how many entries it can holdrequired(int*) — output: the real number of entries in the snapshot (filled in even when capacity is insufficient)generation(uint32_t*) /revision(uint64_t*) — output: snapshot generation and revision numbersource_flags(uint32_t*) — output: parameter source flagsexpected_generation/expected_revision— the generation and revision number the caller read, used for the optimistic concurrency comparison on replace
ReadStartupSnapshot() returns failure when capacity is too small, required still holds the complete real count, and the buffer holds no truncated partial result. Treating the failure as success and using the buffer gives you an incomplete set of startup parameters.
These two entry points only read a snapshot and replace a snapshot as a whole; they do not push anything to the slaves. Parameters take effect only through the startup parameter apply path (slave_startup::apply_startup_params_all() and so on). A rejected replace is normal semantics (another owner just changed it): read the snapshot again and retry rather than bypassing the concurrency check and writing anyway.
Example:
using namespace darra::ethercat;
uint16_t mi = master.MasterNumber();
uint16_t si = 1;
// 1) Probe the real entry count first: do not truncate when the capacity is short, required still holds the full count
int required = 0;
uint32_t generation = 0;
uint64_t revision = 0;
uint32_t source_flags = 0;
int rc = slave_startup::ReadStartupSnapshot(mi, si, nullptr, 0, &required,
&generation, &revision, &source_flags);
if (rc != 0 && required > 0) {
// 2) Grow to the real entry count and re-read, so you always get a complete snapshot
std::vector<ec_startup_param_t> params(static_cast<size_t>(required));
rc = slave_startup::ReadStartupSnapshot(mi, si, params.data(), required, &required,
&generation, &revision, &source_flags);
if (rc != 0) {
printf("读取启动参数快照失败: %d\n", rc); // Reading the startup parameter snapshot failed: %d
return -1;
}
// 3) After editing, replace optimistically by (generation, revision)
uint64_t new_revision = 0;
if (slave_startup::ReplaceStartupSnapshot(mi, si, params.data(), required,
generation, revision, &new_revision) != 0) {
printf("替换被拒: 快照已被其他 owner 改动, 重新读取后再试\n"); // Replacement rejected: the snapshot has been changed by another owner, re-read it and try again
} else {
printf("替换成功, 新修订号=%llu\n", // Replacement succeeded, new revision number=%llu
static_cast<unsigned long long>(new_revision));
}
}
Complete example
#include "ethercat.hpp"
using namespace darra;
int main() {
try {
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}");
master.Build();
// Get the configuration object
auto& config = master.GetConfig();
// Configure the cycle to 125 µs
config.LoopCycle(125000);
// Frame high priority
config.FrameHighPriority(true);
// Watchdog
config.ProcessDataWatchdogMs(100);
// Drift compensation
config.DriftCompensation(true, 1000, 512);
// Switch to OP
master.SetState(EcState::OP);
master.Start();
printf("运行中...\n"); // Running...
getchar();
} catch (const ethercat::DarraException& e) {
printf("错误: %s\n", e.what()); // Error: %s
return -1;
}
return 0;
}
Timeout configuration best practices
The many timeout fields involved in EtherCAT communication are independent of each other and directly affect both how sensitively network faults are detected and how long recovery takes. The table below sums up the common fields, their typical defaults and the recommended ranges. When you deploy, balance three dimensions: network length / interference level / how much you prioritise real-time behaviour.
Key fields at a glance:
| Field | Unit | Default | Recommended range | Effect |
|---|---|---|---|---|
| LoopCycle | ns | 1,000,000 (1ms) | 125,000 ~ 4,000,000 (125 µs ~ 4ms) | PDO cycle; sets the refresh rate and the CPU load |
| TimeoutInitToPreOp | ms | 0 (=3000) | 3000 ~ 10000 | INIT→PREOP wait time (slow slaves / EEPROM loading) |
| TimeoutPreOpToSafeOp | ms | 0 (=10000) | 10000 ~ 30000 | PREOP→SAFEOP wait time (includes SM/FMMU/PDO mapping; increase it on large networks) |
| TimeoutSafeOpToOp | ms | 0 (=10000) | 10000 ~ 15000 | SAFEOP→OP wait time |
| ProcessDataWatchdogMs | ms | 0 (slave default ≈100) | LoopCycle × 10 ~ 100 | How long a slave waits before falling back to SafeOp after losing the master connection |
| PdiWatchdogMs | ms | 0 (slave default) | 0 ~ 200 | Detection window for the slave's local firmware stopping its ESC access |
When to increase or decrease
Increase for:
- Long cables / across cabinets / across a workshop — large physical transmission delay, so occasional RTT jitter needs headroom
- High EMI / welding / near high-power inverters — noise causes occasional frame loss, so allow more room for retries
- VLAN / TSN composite networks — switches add queuing jitter
- Large networks (>50 slaves) —
TimeoutPreOpToSafeOpmust be increased, otherwise the SafeOp transition fails - Slow slaves (large FoE downloads / EEPROM writes) — both the mailbox and Init→PreOp need longer values
Decrease for:
- Fast fault detection first — industrial emergency-stop scenarios; set the watchdog to 5×LoopCycle to detect frame loss within 50ms
- Short desktop cables / lab — RTT is very low, so the watchdog can go down to 20~50ms
- Tight real-time budgets (≤ 250 µs cycles) — the whole timetable is compact, so every timeout must be short
Four presets: default, lab, industrial, high EMI
auto& config = master.GetConfig();
// (1) SDK default - standard short cable + desk to ordinary workshop
config.LoopCycle(1000000); // 1ms
config.TimeoutPreOpToSafeOp(0); // = 10000ms
config.ProcessDataWatchdogMs(0); // Slave default (~100 ms)
// (2) Lab high speed - short cable + demanding RT
config.LoopCycle(250000); // 250 µs
config.TimeoutPreOpToSafeOp(5000);
config.ProcessDataWatchdogMs(20); // Very fast detection
// (3) Typical industrial - long cable + large network
config.LoopCycle(1000000);
config.TimeoutPreOpToSafeOp(20000); // Relaxed for large networks
config.ProcessDataWatchdogMs(200);
// (4) High EMI / welding site - tolerates occasional frame loss
config.LoopCycle(2000000); // 2ms
config.TimeoutPreOpToSafeOp(30000);
config.ProcessDataWatchdogMs(500);
config.AdaptiveTimeoutEnabled(true); // Adaptively absorb jitter
- Timeout too large — a real fault is only reported when the timeout expires, so application alarms / safety stops are delayed
- Timeout too small — occasional jitter is misread as a fault, firing frequent
PDOFrameLoss/StateChangenuisance alarms - Watchdog below a few multiples of LoopCycle — it fires during normal operation and slaves keep falling back to SafeOp
- After any change, run a 24h communication stress test before going live
With AdaptiveTimeoutEnabled(true) (on by default) the SDK computes the per-frame PDO timeout from the real RTT,
so you do not have to tighten LoopCycle by hand. The watchdog / state transition fields above still need per-scenario values.