PDO inputs and outputs
Get the process image pointer through GetIO, and process data element views through PDOArrayFromFrame / PDOArrayItem.
A PDO is one segment of the process image, exchanged automatically by the real-time communication layer every cycle.
The hot path is to reinterpret the pointer returned by GetIO as a packed struct overlay — zero-copy:
- Reading or writing a member reads or writes the process image itself: no copying, no refresh.
- A read always sees the current cycle; a write is sent in the next cycle.
When you need a single fixed-width scalar at a byte offset, use an element view (ec_pdo_array_t / ec_pdo_data_item_t + PDOArrayItem + PDOItemRead* /
PDOItemWrite*).
Mailbox communication (SDO/CoE/FoE and so on) rides along with the PDO cycle automatically and does not consume an extra frame. Mailbox responses take about 2 PDO cycles.
- A view, not a copy: a view holds only four fields —
frame/size/offset/is_input— and stores no data bytes itself; an element is a handle to that one byte in the process image. Steady state is allocation-free; callers usually keep it on the stack. - The view does not own the frame: this family does not copy, hold or free the frame; the caller owns the frame lifetime and thread safety. A live slice becomes invalid as soon as the master releases or changes generation; never cache it across generations.
- Failure semantics: element accessors always return
FALSEand do not modify the out parameter — they never fold the value to 0, never silently read 1 byte, never report half a result. - The write side only accepts outputs: only output-side (RxPDO) windows are writable; calling a write accessor on an input-side view always returns
FALSE(the master overwrites the input area every cycle, so writing it has no effect). - Index overruns and width overruns are reported separately: with
PDOArrayItem, a byte index past the end and "the type width does not fit at the element start" are two distinct failures, so you can tell a wrong byte from a wrong type.
Usage examples
Day-to-day usage
① Struct mapping (zero-copy, keep using it): after entering OP, call GetIO once to get the process image pointer, reinterpret it as a packed
struct pointer, and then read and write it like a variable.
uint16_t m = EcInitFromFile("C:\\EtherCAT\\MyProject.json"); /* one-step JSON initialization (enters OP by default) */
#pragma pack(push, 1)
typedef struct {
uint16_t status_word;
int32_t actual_position;
} in_pdo_t;
typedef struct {
uint16_t control_word;
int32_t target_position;
} out_pdo_t;
#pragma pack(pop)
int32_t out_size = 0, in_size = 0;
uint8_t *out_ptr = NULL, *in_ptr = NULL;
if (!ec_pdo_io_is_ok(GetIO(m, 1, &out_size, &out_ptr, &in_size, &in_ptr)))
return 1; /* not in OP, or the process image is unavailable */
if ((size_t)in_size < sizeof(in_pdo_t) || (size_t)out_size < sizeof(out_pdo_t))
return 1; /* struct larger than the IO area: it would overrun another slave */
in_pdo_t *in = (in_pdo_t *)in_ptr; /* map onto the process image (zero-copy) */
out_pdo_t *out = (out_pdo_t *)out_ptr;
out->control_word = 0x000F; /* write: sent in the next cycle */
out->target_position = in->actual_position + 1000; /* read: current cycle */
② Element view (read one fixed-width value at an offset): take an input frame snapshot first, then build an array view on the snapshot and take an element view.
uint8_t frame[64];
uint32_t copied = 0, required = 0;
uint8_t st = CopySlaveInputPdo(m, 1, frame, (uint32_t)sizeof frame, &copied, &required);
if (ec_pdo_io_is_ok(st)) {
ec_pdo_array_t arr;
ec_pdo_data_item_t item;
uint16_t sw = 0;
if (PDOArrayFromFrame(frame, (int32_t)copied, TRUE, &arr) /* TRUE = input side: read-only */
&& PDOArrayItem(&arr, 0, &item) /* element view at offset 0 */
&& PDOItemReadUInt16(&item, &sw)) /* little-endian, 2 bytes */
printf("status=0x%04X\n", sw);
} else if (ec_pdo_io_is_buffer_too_small(st)) {
printf("输入帧 %u 字节,缓冲区扩容后重试\n", required); /* Input frame %u bytes, retry after growing the buffer */
}
③ Writing outputs with an element view: the output side does not allow a partial read-modify-write on a live slice; use a versioned transaction (Copy → patch → Commit).
uint8_t out_frame[64]; /* if the buffer is too small, grow it to the full frame length given by required */
uint32_t copied = 0, required = 0;
uint64_t ticket = 0, deadline = 0, token = 0; /* first Begin: pass 0 for ticket / deadline and the SDK issues them */
uint8_t st = CopySlaveOutputPdoVersioned(m, 1, out_frame, (uint32_t)sizeof out_frame,
&copied, &required, &ticket, &deadline, &token);
if (ec_pdo_io_is_ok(st)) {
ec_pdo_array_t arr;
ec_pdo_data_item_t item;
if (PDOArrayFromFrame(out_frame, (int32_t)copied, FALSE, &arr) /* FALSE = output side: writable */
&& PDOArrayItem(&arr, 2, &item)) {
if (!PDOItemWriteInt16(&item, 1500)) /* patch: changes the frame buffer only, not yet on the bus */
printf("patch 被拒:该元素放不下 2 字节\n"); /* patch rejected: this element cannot hold 2 bytes */
}
uint64_t current = 0;
uint32_t written = 0, need = 0;
if (!ec_pdo_io_is_ok(CommitSlaveOutputPdoVersioned(m, 1, out_frame, copied, token,
ticket, deadline,
¤t, &written, &need)))
printf("提交失败:written=%u required=%u\n", written, need); /* Commit failed: written=%u required=%u */
}
Cyclic changes
One mapping is enough; put the same mapping straight into your own cycle loop and use it directly:
while (running) {
out->control_word = (in->status_word & 0x0004) ? 0x000F : 0x0006;
out->target_position = in->actual_position;
wait_next_tick(); /* your own cadence, for example 1 ms */
}
The real-time communication layer moves process data every cycle: what you read in the loop is always the current cycle, what you write is sent in the next cycle, no extra call is needed, and you must not re-fetch
GetIO on every tick. The old mapping only becomes invalid after Dispose / a master generation change / re-entering OP; when you re-enter OP, fetch it once more.
Element views work the other way around — a view is bound to the window you hand it: a snapshot frame does not change by itself, so you must take a new frame for a new tick; a live slice points at the process image itself, its values follow the bus, so you do not need to re-fetch it every tick, but you must re-fetch it after release / a generation change.
Process image access
GetIO()
uint8_t GetIO(uint16_t master_index, uint16_t slave_index,
int32_t* out_byte_size, uint8_t** out_byte,
int32_t* in_byte_size, uint8_t** in_byte);
Returns the slave's live IOmap pointers: out_byte is the output process image (a write is sent out), in_byte is the input process image (refreshed by the bus). This is the entry to the zero-copy hot path; use it with a packed struct overlay.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-basedout_byte_size(int32_t*) — out parameter, receives the number of output process image bytesout_byte(uint8_t**) — out parameter, receives the base address of the output process imagein_byte_size(int32_t*) — out parameter, receives the number of input process image bytesin_byte(uint8_t**) — out parameter, receives the base address of the input process image
Return value:
uint8_t— status code,0x00on success; always test it withec_pdo_io_is_ok(), never compare it againstEC_PDO_IO_*names
Description:
- On failure (a non-success status, or a
NULLpointer because the runtime is not ready) never dereferenceout_byte/in_byte. - After you get the pointers, check the struct size against
*_byte_sizebefore overlaying. - The pointers map onto the IOmap; they become invalid after the master releases or changes generation.
- The input area is read-only: the master overwrites the I area pointed to by
in_bytefrom the slave every cycle, so writing it has no effect (the next cycle wipes it). For read-only consumption (decode / test / forward) useGetIORO, whose out parameter isconst uint8_t**and closes the write path at the type level; write process data only through the output side (out_byte/PDOSliceOutputPtr/WriteSlaveOutputPdo/ versioned transactions). - The input direction also needs a freshness check: after a slave goes offline the I area keeps the last frame from before the drop under "input stability" — the address and the length are still there, but those bytes are no longer the current value. To take the pointer and judge the offline state in one call use
GetInputsPtrIfFresh(); if you already hold a pointer, re-check withGetSlaveIsLost(). A stale frame must never be used as the current value.
Example:
int32_t out_size = 0, in_size = 0;
uint8_t *out_ptr = NULL, *in_ptr = NULL;
if (ec_pdo_io_is_ok(GetIO(m, 1, &out_size, &out_ptr, &in_size, &in_ptr))
&& out_ptr && in_ptr && in_size >= 2 && out_size >= 1) {
uint16_t sw = (uint16_t)(in_ptr[0] | (in_ptr[1] << 8)); /* read input: current cycle, little-endian */
out_ptr[0] = 0x0F; /* write output: sent in the next cycle */
printf("sw=0x%04X\n", sw);
}
GetInputsPtrIfFresh()
BOOL GetInputsPtrIfFresh(uint16_t master_index, uint16_t slave_index,
const uint8_t** in_byte, int32_t* in_byte_size);
Takes the input process image pointer and, in the same call, judges whether this frame can be used as the current value.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-basedin_byte(const uint8_t**) — out parameter, receives the base address of the input process image; may beNULLto skip filling in that directionin_byte_size(int32_t*) — out parameter, receives the number of input process image bytes; may beNULL
Return value:
BOOL—TRUE= the pointer is usable and the data is not stale;FALSE= the image is unavailable, or the slave is offline
Description:
- Three situations return
FALSE; any one of them is enough:- The status is not success (the same values as
ec_pdo_io_is_ok():0x00on the wire / contract code1); - The input pointer is
NULLor the length is<= 0(not mapped / not in OP); GetSlaveIsLost()rules that the slave is offline.
- The status is not success (the same values as
- On success,
*in_byte/*in_byte_sizegive the same page and the same length asGetIORO. - On failure both out parameters are set to
NULL/0; no value is left over from the previous call, and no dangling pointer is left behind. - The only source of the online verdict is the slave-liveness three-state (
GetSlaveIsLost()): it is true only when a measurement actually rules LOST; with no measurement evidence it truthfully reports "not lost", so "not measured" is never mistaken for offline and never damages a normal cycle. - It applies to the input direction only: the output area is the master's own shadow frame, and a slave going offline does not affect its validity. For an output pointer use
GetIO/GetIORO, which apply no offline interception. - It judges only the moment the pointer is taken. A caller that caches the pointer outside the cycle and reuses it across cycles must still re-check with
GetSlaveIsLost()itself.
Example:
const uint8_t* in_ptr = NULL;
int32_t in_size = 0;
if (GetInputsPtrIfFresh(m, 1, &in_ptr, &in_size) && in_size >= 2) {
uint16_t sw = (uint16_t)(in_ptr[0] | (in_ptr[1] << 8)); /* the current cycle's value */
printf("sw=0x%04X\n", sw);
} else {
/* the image is unavailable, or the slave is offline: this frame cannot be used as the current value, take the failure branch */
}
ec_pdo_io_is_ok() / ec_pdo_io_is_buffer_too_small()
BOOL ec_pdo_io_is_ok(uint8_t status);
BOOL ec_pdo_io_is_buffer_too_small(uint8_t status);
The only correct way to judge process data status codes. The whole-frame functions and GetIO share the same success code 0x00; the two helpers additionally accept the contract codes (1
/ 2); always judge through them.
Parameters:
status(uint8_t) — return value ofGetIOor of a whole-frame function
Return value:
BOOL—ec_pdo_io_is_ok: treats both success code0x00and contract code1as success;ec_pdo_io_is_buffer_too_small: treats both0xFDand contract code2as buffer too small
Description:
- When the buffer is too small it does not copy a partial frame;
required_sizegives the full frame length, so grow the buffer to it and retry. - At run time you only get status codes back:
0x00on success, failure classes0xFA..0xFF.1..6are the contract values ofec_pdo_io_status_t(master/core.h), do not compare the rawstatusagainstEC_PDO_IO_*names —EC_PDO_IO_OKdoes not catch the success code, whileEC_PDO_IO_FAILEDhas the same value0as success. - Every other status (length mismatch, version conflict, invalidated generation, IOmap busy) is a failure.
- On the input direction a dropped slave returns
0xFB(Stale): the interface itself is fine, but the data may be the last frame before the drop, so treat it as "possibly stale" and distinguish it from a real call failure such as FAILED/BUSY.
Example:
uint32_t copied = 0, required = 0;
uint8_t st = CopySlaveInputPdo(m, 1, frame, (uint32_t)sizeof frame, &copied, &required);
if (ec_pdo_io_is_ok(st))
printf("这一拍 %u 字节\n", copied); /* This cycle %u bytes */
else if (ec_pdo_io_is_buffer_too_small(st))
printf("需要 %u 字节的缓冲\n", required); /* A buffer of %u bytes is needed */
PDOSliceInputPtr()
BOOL PDOSliceInputPtr(uint16_t master_index, uint16_t slave_index,
int32_t offset, int32_t size,
const uint8_t** slice);
Takes a read-only slice view of size bytes at byte offset offset in the live input process image (zero-copy).
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-basedoffset(int32_t) — byte offset from the start of this slave's input process imagesize(int32_t) — slice size in bytes, must be> 0slice(const uint8_t**) — out parameter, receives the slice base address
Return value:
BOOL—TRUEon success- Out of range (
offset < 0,size <= 0,offset + sizebeyond the image for that direction) or an unavailable image returnsFALSE, with*sliceset toNULL— it never returns a pointer outside the image
- Out of range (
Description: The result is a const view: the master overwrites the input area from the slave every cycle, so writing it has no effect; to write process data use the output side.
PDOSliceInputPtr returns a const uint8_t*.
To build element views on it you must explicitly cast away const, and only for reading — a view with is_input = TRUE makes every write accessor return
FALSE, so the read-only constraint is still enforced by the SDK.
Example:
const uint8_t* slice = NULL;
if (PDOSliceInputPtr(m, 1, 0, 4, &slice)) {
ec_pdo_array_t arr;
ec_pdo_data_item_t item;
uint32_t value = 0;
if (PDOArrayFromFrame((uint8_t *)(uintptr_t)slice, 4, TRUE, &arr)
&& PDOArrayItem(&arr, 0, &item)
&& PDOItemReadUInt32(&item, &value))
printf("value=%u\n", value); /* every access reads the current image */
}
PDOSliceOutputPtr()
BOOL PDOSliceOutputPtr(uint16_t master_index, uint16_t slave_index,
int32_t offset, int32_t size,
uint8_t** slice);
Takes a slice view of size bytes at byte offset offset in the live output process image; a write goes straight back. The range rules are the same as for PDOSliceInputPtr.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-basedoffset(int32_t) — byte offset from the start of this slave's output process imagesize(int32_t) — slice size in bytes, must be> 0slice(uint8_t**) — out parameter, receives the slice base address
Return value:
BOOL—TRUEon success; out of range or an unavailable image returnsFALSE, with*sliceset toNULL
Description: This is a live write window, suitable for overwriting a whole segment. A partial read-modify-write (RMW) on a live output slice is forbidden — partial overwrites / bit operations inside the slice must go through a versioned transaction.
Example:
uint8_t* out_slice = NULL;
if (PDOSliceOutputPtr(m, 1, 0, 2, &out_slice)) {
ec_pdo_array_t arr;
ec_pdo_data_item_t item;
if (PDOArrayFromFrame(out_slice, 2, FALSE, &arr)
&& PDOArrayItem(&arr, 0, &item)
&& PDOItemWriteUInt16(&item, 0x000F))
printf("已写入输出切片\n"); /* Output slice written */
}
Frame sources and freshness
Element views are bound to a process image byte window held by the caller. A window has three sources, and element accessors treat all three alike — they only know the window, not where it came from:
- Snapshot frame (recommended): the whole frame copied out by
CopySlaveInputPdo/CopySlaveOutputPdo. This is a generation-scoped consistent read: one successful call yields a self-consistent whole frame, and an undersized buffer never copies a partial frame. - Versioned output frame: the frame taken by
CopySlaveOutputPdoVersioned; after patching it must be committed byCommitSlaveOutputPdoVersioned, and in between it lives only in your buffer, never on the bus. - Live slice: the process image itself, pointed to by
PDOSliceInputPtr/PDOSliceOutputPtr, zero-copy; you read the value as of the moment of access.
Freshness is decided by the window, not by the accessor. The SDK does not take snapshots for you: one accessor call just takes one value from the bound window.
- When a view is bound to a snapshot frame, every read during its lifetime sees the same frame — multiple fields are consistent by construction, but it does not change by itself, so you must take a new frame for a new tick.
- When a view is bound to a live slice, every accessor call reads the current image directly, so two accesses in the same expression may land in two different bus cycles (for example, when you combine the reads of two elements into one expression, the bus may already have refreshed once between them).
When you need a view in which multiple fields are consistent with each other within one tick, take a whole-frame snapshot with CopySlaveInputPdo and build the array view on that buffer; or use the
packed struct overlay from GetIO and read the whole direction in one go.
Element accessors are not a zero-copy hot path.
The entries for zero-copy reads of the process image are GetIO (packed struct overlay) and PDOSliceInputPtr / PDOSliceOutputPtr (slice by offset).
Element accessors are a tool for "decode one fixed-width scalar at an offset": they do not copy bytes themselves, but they do not guarantee consistency for you either — they read exactly the window you hand them.
For a safe whole view of the live image, use the overlay, not element accessors field by field.
Input frames while a slave is offline
After a slave goes offline the I area keeps the last frame from before the drop, per "input stability": the address is still there and the length is still there, so dereferencing it will not crash, but those bytes are no longer the current value. All three entries take the same position on this:
- Zero-copy input (
in_bytefromGetIO,GetIORO,PDOSliceInputPtr, packed struct overlay): the address itself does not tell you that it has gone stale. You must judgeec_pdo_io_is_ok(st)and freshness together — take the pointer and the offline verdict in one call withGetInputsPtrIfFresh(), or re-check withGetSlaveIsLost()yourself. A stale frame must never be used as the current value. - Snapshot:
CopySlaveInputPdo()returnsEC_PDO_IO_STALE(0xFBon the wire) while the slave is offline — the interface is fine, but the data may be the last frame before the drop. This is separate from real call failures such as FAILED / BUSY, and the caller must treat them differently. - The output direction is unaffected: the output area is the master's own shadow frame, not a slave measurement, so an offline slave does not invalidate it;
GetIO/GetIOROapply no offline interception in the output direction. The STALE verdict likewise applies to the input direction only.
Whole-frame snapshots and versioned transactions
CopySlaveInputPdo() / CopySlaveOutputPdo()
uint8_t CopySlaveInputPdo(uint16_t master_index, uint16_t slave_index,
uint8_t* buffer, uint32_t buffer_size,
uint32_t* copied_size, uint32_t* required_size);
uint8_t CopySlaveOutputPdo(uint16_t master_index, uint16_t slave_index,
uint8_t* buffer, uint32_t buffer_size,
uint32_t* copied_size, uint32_t* required_size);
Copies one direction's PDO frame into your own buffer, giving a consistent snapshot from a single generation.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-basedbuffer(uint8_t*) — caller's receive bufferbuffer_size(uint32_t) — buffer size in bytescopied_size(uint32_t*) — out parameter, number of bytes actually copiedrequired_size(uint32_t*) — out parameter, full frame length (grow the buffer to it when it is too small)
Return value:
uint8_t— status code, judge it withec_pdo_io_is_ok()/ec_pdo_io_is_buffer_too_small()
Description: When the buffer is too small no bytes are copied at all, and required_size
gives the authoritative length. The snapshot is your memory: once copied it does not follow the bus, so you can parse it at leisure and pass it across threads; this is the preferred frame source when you need a consistent multi-field view.
Example:
uint8_t frame[128];
uint32_t copied = 0, required = 0;
if (ec_pdo_io_is_ok(CopySlaveInputPdo(m, 1, frame, (uint32_t)sizeof frame, &copied, &required))) {
ec_pdo_array_t arr;
if (PDOArrayFromFrame(frame, (int32_t)copied, TRUE, &arr))
printf("这一拍 %d 字节的视图就绪\n", PDOArrayLength(&arr)); /* The %d byte view for this cycle is ready */
}
WriteSlaveOutputPdo()
uint8_t WriteSlaveOutputPdo(uint16_t master_index, uint16_t slave_index,
const uint8_t* data, uint32_t size,
uint32_t* written_size, uint32_t* required_size);
Replaces the slave's output process image exactly with the complete RxPDO frame you hold (the whole-frame write entry for a single real-time owner).
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-baseddata(const uint8_t*) — the complete output frame to writesize(uint32_t) — frame size in bytes, must equal the current full frame lengthwritten_size(uint32_t*) — out parameter, number of bytes actually writtenrequired_size(uint32_t*) — out parameter, the current full frame length
Return value:
uint8_t— status code, judge it withec_pdo_io_is_ok(); whensizedoes not match the current full frame length it returns a length-mismatch status and writes no bytes
Description: Fixed-length whole-frame replacement, no read-modify-write — when you only change a few fields, use a versioned transaction.
Example:
uint8_t frame[64]; /* full output frame; the length must match the current frame */
uint32_t written = 0, required = 0;
if (!ec_pdo_io_is_ok(WriteSlaveOutputPdo(m, 1, frame, (uint32_t)sizeof frame,
&written, &required)))
printf("写入被拒:written=%u required=%u\n", written, required); /* Write rejected: written=%u required=%u */
CopySlaveOutputPdoVersioned() / CommitSlaveOutputPdoVersioned()
uint8_t CopySlaveOutputPdoVersioned(uint16_t master_index, uint16_t slave_index,
uint8_t* buffer, uint32_t buffer_size,
uint32_t* copied_size, uint32_t* required_size,
uint64_t* transaction_ticket,
uint64_t* deadline_us,
uint64_t* version_token);
uint8_t CommitSlaveOutputPdoVersioned(uint16_t master_index, uint16_t slave_index,
const uint8_t* data, uint32_t size,
uint64_t expected_token,
uint64_t transaction_ticket,
uint64_t deadline_us,
uint64_t* current_token,
uint32_t* written_size,
uint32_t* required_size);
An optimistic-concurrency RxPDO transaction: Begin takes an output frame and brings back a version token, you patch the local buffer, then Commit it. This is the only legal entry for partial / typed / bit / bulk read-modify-write.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-basedbuffer(uint8_t*) /data(const uint8_t*) — Begin's receive buffer / the frame to commitbuffer_size(uint32_t) /size(uint32_t) — buffer size in bytes / commit frame lengthcopied_size(uint32_t*) /written_size(uint32_t*) — out parameters, bytes actually copied / bytes actually writtenrequired_size(uint32_t*) — out parameter, full frame lengthtransaction_ticket(uint64_t*) — out parameter (Begin) / input (Commit): an opaque transaction ticket issued by the SDKdeadline_us(uint64_t*) — out parameter (Begin) / input (Commit): an absolute deadline on the SDK's monotonic clockversion_token(uint64_t*) — out parameter (Begin) / passed in asexpected_token(Commit)- the high 32 bits are the context generation, the low 32 bits are this slave's output revision; neither of them is 0
current_token(uint64_t*) — out parameter, the authoritative current version token
Return value:
uint8_t— status code, judge it withec_pdo_io_is_ok(); on conflict / invalidation / length mismatchwritten_sizeis 0 and the authoritativecurrent_token/required_sizeare returned
Description:
- On the first Begin pass 0 for both
transaction_ticketanddeadline_us; the SDK issues a non-zero ticket and sets an absolute deadline ofnow + 5000 us. - The size query, re-Begin, retry after failure and Commit of the same read-modify-write must reuse these two values unchanged; zeroing them to extend the deadline, or forging them, is forbidden.
- Only the SDK can rule on whether a Commit that already produced side effects has timed out; once Commit returns success, the caller must not re-judge it as failed with a local clock.
- Exact whole-frame replacement (a single real-time owner already holds the complete authoritative RxPDO) →
WriteSlaveOutputPdo; whensizedoes not match the current full frame length it returns a length-mismatch status and writes no bytes. - Partial / typed / bit / bulk read-modify-write → the versioned transaction pair in this section.
WriteSlaveOutput/WriteSlaveOutputByte/PDOWriteDirect/PDOBatchWriteare all retired entries:- fixed fail-closed, they write no output, and they return a failure status:
WriteSlaveOutput/WriteSlaveOutputBytealways0xFF,PDOWriteDirectalwaysFALSE,PDOBatchWritealways0(= 0 successful writes). Callers must check the return value. - the first two differ from the real entry
WriteSlaveOutputPdoonly in their suffix.
- fixed fail-closed, they write no output, and they return a failure status:
- Their read-side twins
PDOReadDirect/PDOBatchReadare live entries: they only fill the caller's buffer with a whole input frame snapshot, write no output, and are not retired.
Example:
uint64_t ticket = 0, deadline = 0, token = 0;
uint64_t current = 0;
uint32_t copied = 0, required = 0, written = 0, need = 0;
if (ec_pdo_io_is_ok(CopySlaveOutputPdoVersioned(m, 1, frame, (uint32_t)sizeof frame,
&copied, &required, &ticket, &deadline, &token))) {
/* patch the frame through element views (see the "Element views" section) ... */
if (!ec_pdo_io_is_ok(CommitSlaveOutputPdoVersioned(m, 1, frame, copied, token,
ticket, deadline,
¤t, &written, &need)))
printf("提交失败:current=0x%llX written=%u required=%u\n", /* Commit failed: current=0x%llX written=%u required=%u */
(unsigned long long)current, written, need);
}
CopySlaveOutputPdoVersionedChecked() / CommitSlaveOutputPdoVersionedChecked()
uint8_t CopySlaveOutputPdoVersionedChecked(uint16_t master_index, uint16_t slave_index,
uint8_t* buffer, uint32_t buffer_size,
uint32_t* copied_size, uint32_t* required_size,
uint64_t* transaction_ticket,
uint64_t* deadline_us,
uint64_t* version_token);
uint8_t CommitSlaveOutputPdoVersionedChecked(uint16_t master_index, uint16_t slave_index,
const uint8_t* data, uint32_t size,
uint64_t expected_token,
uint64_t transaction_ticket,
uint64_t deadline_us,
uint64_t* current_token,
uint32_t* written_size,
uint32_t* required_size);
Checked versioned output frame read / commit: the parameter list matches the versioned transaction above without the Checked suffix one for one, and the read and write semantics are the same; the difference is that both the read-back and the commit are checked — the read-back validates the transaction ticket / deadline / version token, and the commit only takes effect while the frame's expected_token is still the current version.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-basedbuffer(uint8_t*) /data(const uint8_t*) — read: the caller's receive buffer; commit: the frame to commitbuffer_size(uint32_t) /size(uint32_t) — buffer size in bytes / commit frame lengthcopied_size(uint32_t*) /written_size(uint32_t*) — out parameters, bytes actually copied / bytes actually writtenrequired_size(uint32_t*) — out parameter, full frame lengthtransaction_ticket(uint64_t*) — out parameter (read) / input (commit): the transaction ticket issued by the SDKdeadline_us(uint64_t*) — out parameter (read) / input (commit): an absolute deadline on the SDK's monotonic clockversion_token(uint64_t*) — out parameter (read) / passed in asexpected_token(commit)current_token(uint64_t*) — out parameter, the authoritative current version token
Return value:
uint8_t— status byte, same asec_pdo_io_status,0= OK; always judge it withec_pdo_io_is_ok()
Description:
- Choosing between this pair and the version without the Checked suffix: use this pair when you need "ticket / deadline / version token" as hard constraints; both only handle versioned output frame transactions, and neither allows a partial read-modify-write on a live output slice.
- On the first read-back
transaction_ticketanddeadline_usmust both be 0 and are issued together by the SDK; later re-reads, retries and commits reuse the same pair, and supplying only one of them is treated as a contract violation. - A single frame is capped at 64 KB; a mismatched ticket / deadline pair, an invalid token, self-contradictory output and other violations all return
0xFFand zero the out parameters (fail-closed). - When the commit is rejected (version advanced / length mismatch)
written_sizeis 0 andcurrent_token/required_sizegive the authoritative values; the caller should start a new transaction with the new token rather than retrying the old one. - When the SDK is not ready it returns
0xFF(a failure class), not success; do not read that as a "version conflict".
Example:
uint8_t frame[64];
uint32_t copied = 0, required = 0, written = 0, need = 0;
uint64_t ticket = 0, deadline = 0, token = 0, current = 0;
uint8_t st = CopySlaveOutputPdoVersionedChecked(m, 1, frame, (uint32_t)sizeof frame,
&copied, &required, &ticket, &deadline, &token);
if (ec_pdo_io_is_ok(st)) {
/* patch the frame (see the "Element views" section) ... */
if (!ec_pdo_io_is_ok(CommitSlaveOutputPdoVersionedChecked(m, 1, frame, copied, token,
ticket, deadline,
¤t, &written, &need)))
printf("提交被拒:current=0x%llX written=%u required=%u\n", /* Commit rejected: current=0x%llX written=%u required=%u */
(unsigned long long)current, written, need);
}
Element views
PDOArrayFromFrame()
BOOL PDOArrayFromFrame(uint8_t* frame, int32_t size, BOOL is_input, ec_pdo_array_t* array);
Builds an array view on a process image byte window held by the caller. This function does not copy, hold or free the frame.
Parameters:
frame(uint8_t*) — window base address (snapshot frame buffer or live slice), held by the callersize(int32_t) — usable bytes in the window = process image bytes for this direction; pass0when not in OP / not mapped, in which case every index is out of rangeis_input(BOOL) —TRUE= input side (TxPDO, read-only);FALSE= output side (RxPDO, writable)array(ec_pdo_array_t*) — out parameter, receives the array view
Return value:
BOOL—TRUEon success; returnsFALSEwhenframe/arrayisNULLorsize < 0
Example:
ec_pdo_array_t arr;
if (PDOArrayFromFrame(frame, (int32_t)copied, TRUE, &arr))
printf("输入过程映像 %d 字节\n", PDOArrayLength(&arr)); /* Input process image %d bytes */
Related structures:
typedef struct {
uint8_t* frame; /* window base (caller-owned; not copied, not freed) */
int32_t size; /* usable bytes in the window = process image bytes for this direction; not in OP = 0 */
BOOL is_input; /* TRUE = input side (TxPDO, read-only) / FALSE = output side (RxPDO) */
} ec_pdo_array_t;
PDOArrayLength()
int32_t PDOArrayLength(const ec_pdo_array_t* array);
The number of bytes in the process image for this direction.
Parameters:
array(const ec_pdo_array_t*) — array view
Return value:
int32_t— byte count; 0 whenarrayisNULL, or when not in OP / not mapped
Example:
for (int32_t i = 0; i < PDOArrayLength(&arr); i++) {
ec_pdo_data_item_t item;
if (PDOArrayItem(&arr, i, &item))
printf("偏移 %d 可访问\n", i); /* Offset %d is accessible */
}
PDOArrayItem()
BOOL PDOArrayItem(const ec_pdo_array_t* array, int32_t index, ec_pdo_data_item_t* item);
Takes an element view at a byte offset; index is relative to the start of the process image for this direction and starts at 0. An element view only holds a handle, not the data bytes.
Parameters:
array(const ec_pdo_array_t*) — array viewindex(int32_t) — byte offset, in the range[0, PDOArrayLength(array))item(ec_pdo_data_item_t*) — out parameter, receives the element view
Return value:
BOOL—TRUEon success; returnsFALSEwhenarray/itemisNULL, the window base isNULL, orindexis out of range
Description: What is rejected here is "byte offset out of range". Once you have the element view, the accessor checks again whether "that width fits at the element start"; the two failures are deliberately reported separately.
Example:
ec_pdo_data_item_t item;
if (PDOArrayItem(&arr, 6, &item))
printf("偏移 6 的元素视图就绪\n"); /* The element view at offset 6 is ready */
Related structures:
typedef struct {
uint8_t* frame; /* window base (same as ec_pdo_array_t) */
int32_t size; /* usable bytes in the window */
int32_t offset; /* element byte offset (relative to frame) */
BOOL is_input; /* TRUE = input side (TxPDO, read-only) */
} ec_pdo_data_item_t;
Element accessors
The in-header wrappers for the offset-based single-scalar interfaces (PdoRead* / PdoWrite* / PDOReadInput* / PDOWriteOutput*) have been removed from this SDK.
The corresponding low-level EcPdoCodec_* encoding helpers are public protocol utilities; call the public function names directly.
To take a single value at an offset, go through the element view (PDOArrayItem + PDOItemRead* / PDOItemWrite*).
PDOItemReadContent() / PDOItemWriteContent()
BOOL PDOItemReadContent (const ec_pdo_data_item_t* item, uint8_t* value);
BOOL PDOItemWriteContent(const ec_pdo_data_item_t* item, uint8_t value);
The raw value of the element's first byte (1 byte, unsigned). PDOItemReadUInt8 / PDOItemWriteUInt8 are synonymous and touch the same byte.
Parameters:
item(const ec_pdo_data_item_t*) — element viewvalue(uint8_t* / uint8_t) — read: out parameter, not modified on failure; write: the byte to write
Return value:
BOOL—TRUEon success; returnsFALSEwhenvalueisNULL, the offset is out of range, or the view is input-side (write)
Example:
uint8_t raw = 0;
if (PDOItemReadContent(&item, &raw))
printf("byte=0x%02X\n", raw);
if (!PDOItemWriteContent(&out_item, 0x0F)) /* whole-byte overwrite, output side only */
printf("写入被拒:输入侧视图或偏移越界\n"); /* Write rejected: input-side view or offset out of range */
Typed reads (PDOItemRead*())
BOOL PDOItemReadInt8 (const ec_pdo_data_item_t* item, int8_t* value);
BOOL PDOItemReadUInt8 (const ec_pdo_data_item_t* item, uint8_t* value);
BOOL PDOItemReadInt16 (const ec_pdo_data_item_t* item, int16_t* value);
BOOL PDOItemReadUInt16(const ec_pdo_data_item_t* item, uint16_t* value);
BOOL PDOItemReadInt32 (const ec_pdo_data_item_t* item, int32_t* value);
BOOL PDOItemReadUInt32(const ec_pdo_data_item_t* item, uint32_t* value);
BOOL PDOItemReadInt64 (const ec_pdo_data_item_t* item, int64_t* value);
BOOL PDOItemReadUInt64(const ec_pdo_data_item_t* item, uint64_t* value);
BOOL PDOItemReadFloat (const ec_pdo_data_item_t* item, float* value);
BOOL PDOItemReadDouble(const ec_pdo_data_item_t* item, double* value);
Reads one fixed-width scalar starting at the element offset; on the read side any direction of view is legal.
Parameters:
item(const ec_pdo_data_item_t*) — element viewvalue(int8_t* ... double*) — out parameter, receives the value read; not modified on failure
Return value:
BOOL—TRUEon success; returnsFALSEwhenvalueisNULL, the element window cannot fit that width, or the offset is out of range
Description: Multi-byte values are always little-endian (the EtherCAT wire order), and this SDK never byte-swaps them. PDOItemReadInt8 sign-extends
two's complement from 8 bits; floating point is IEEE754.
Example:
int16_t pos = 0;
uint16_t sw = 0;
if (PDOItemReadInt16(&item, &pos))
printf("pos=%d\n", pos); /* 2 bytes from the element offset, little-endian */
if (!PDOItemReadUInt16(&item, &sw))
printf("该元素放不下 2 字节\n"); /* for example when it is already the last byte */
Typed writes (PDOItemWrite*())
BOOL PDOItemWriteInt8 (const ec_pdo_data_item_t* item, int8_t value);
BOOL PDOItemWriteUInt8 (const ec_pdo_data_item_t* item, uint8_t value);
BOOL PDOItemWriteInt16 (const ec_pdo_data_item_t* item, int16_t value);
BOOL PDOItemWriteUInt16(const ec_pdo_data_item_t* item, uint16_t value);
BOOL PDOItemWriteInt32 (const ec_pdo_data_item_t* item, int32_t value);
BOOL PDOItemWriteUInt32(const ec_pdo_data_item_t* item, uint32_t value);
BOOL PDOItemWriteInt64 (const ec_pdo_data_item_t* item, int64_t value);
BOOL PDOItemWriteUInt64(const ec_pdo_data_item_t* item, uint64_t value);
BOOL PDOItemWriteFloat (const ec_pdo_data_item_t* item, float value);
BOOL PDOItemWriteDouble(const ec_pdo_data_item_t* item, double value);
Writes the value into the element's bytes at a fixed width in little-endian. Output side only: an input-side view always returns FALSE and modifies no bytes.
Parameters:
item(const ec_pdo_data_item_t*) — element view, must come from an output-side windowvalue(int8_t ... double) — the value to write
Return value:
BOOL—TRUEon success; returnsFALSEfor an input-side view, when the element window cannot fit that width, or when the offset is out of range
Description: A partial overwrite of a live
output slice (including bit operations) is a partial read-modify-write and is not allowed; overwriting the whole slice in one go is fine. Every other write must land in the frame buffer taken by a versioned transaction, and once patching is
done it is committed by CommitSlaveOutputPdoVersioned.
Example:
/* arr is built on the output frame taken by a versioned transaction (is_input = FALSE) */
ec_pdo_data_item_t item;
if (PDOArrayItem(&arr, 2, &item)) {
if (!PDOItemWriteInt16(&item, 1500)) /* patch the frame buffer */
printf("写入被拒\n"); /* Write rejected */
}
/* patch done, then Commit */
PDOItemReadBool() / PDOItemWriteBool()
BOOL PDOItemReadBool (const ec_pdo_data_item_t* item, BOOL* value);
BOOL PDOItemWriteBool(const ec_pdo_data_item_t* item, BOOL value);
A whole-byte boolean accessor with bit0 semantics: a read is (byte & 0x01) != 0, a write of TRUE = 0x01 / FALSE =
0x00 (a whole-byte overwrite, not a bit operation).
Parameters:
item(const ec_pdo_data_item_t*) — element viewvalue(BOOL* / BOOL) — read: out parameter, not modified on failure; write: the boolean value to write
Return value:
BOOL—TRUEon success; returnsFALSEwhenvalueisNULL, the offset is out of range, or the view is input-side (write)
Description:
- The boolean accessor only looks at the least significant bit: byte
0x00readsFALSE,0x01readsTRUE, while both0x02and0x80readFALSE. - This is not "non-zero is true"; many people trip over it the first time.
- To test truth by the whole byte (0 / anything other than 0), take the raw byte with
PDOItemReadContentand compare it yourself — this SDK provides no second boolean accessor with "non-zero is true" semantics.
Example:
BOOL enable = FALSE;
if (PDOItemReadBool(&item, &enable))
printf("bit0 = %s\n", enable ? "true" : "false"); /* bytes 0x02 / 0x80 are also false */
if (!PDOItemWriteBool(&out_item, TRUE)) /* whole-byte write of 0x01 */
printf("写入被拒\n"); /* Write rejected */
PDOItemReadBit() / PDOItemWriteBit()
BOOL PDOItemReadBit (const ec_pdo_data_item_t* item, int bit_index, BOOL* value);
BOOL PDOItemWriteBit(const ec_pdo_data_item_t* item, int bit_index, BOOL value);
Reads / writes bit bit_index of this element's byte; bit_index is 0..7, with 0 = LSB.
Parameters:
item(const ec_pdo_data_item_t*) — element viewbit_index(int) — bit number0..7, 0 = LSBvalue(BOOL* / BOOL) — read: out parameter, not modified on failure; write: the bit value to write
Return value:
BOOL—TRUEon success; returnsFALSEwhenbit_indexis outside0..7, the offset is out of range, or the view is input-side (write)
Description:
- Bit numbers are addressed by byte, not by element width: no matter how wide the element is,
0..7always refer to that one byte at the element offset (byte 0 of a multi-byte element is the little-endian low byte), and never cross into the next byte. - Writing is allowed on the output side, and only the target bit is overwritten — the other bits of the same byte keep their values.
Example:
BOOL ready = FALSE;
if (PDOItemReadBit(&item, 0, &ready)) /* bit0 of the element byte */
printf("ready=%d\n", ready);
if (!PDOItemWriteBit(&out_item, 0, TRUE)) /* set bit0 only; the other bits in the same byte stay untouched */
printf("写入被拒\n"); /* Write rejected */
if (!PDOItemWriteBit(&out_item, 8, TRUE)) /* bit number out of range: returns FALSE, changes no byte */
printf("位号必须在 0..7\n"); /* Bit number must be within 0..7 */
PDOItemReadValue() / PDOItemWriteValue()
BOOL PDOItemReadValue (const ec_pdo_data_item_t* item,
ec_pdo_datatype_t type, ec_pdo_value_t* value);
BOOL PDOItemWriteValue(const ec_pdo_data_item_t* item,
ec_pdo_datatype_t type, const ec_pdo_value_t* value);
Reads / writes an element by EtherCAT data type — the entry to use when the data type is only known at run time (for example when you are driven by an ESI mapping table).
Parameters:
item(const ec_pdo_data_item_t*) — element viewtype(ec_pdo_datatype_t) —EC_DT_*code valuevalue(ec_pdo_value_t* / const ec_pdo_value_t*) — read: out parameter, take the member matchingtype, not modified on failure; write: read the member matchingtype
Return value:
BOOL—TRUEon success; returnsFALSEwhentypeis not in the supported type table,valueisNULL, the offset / width is out of range, or the view is input-side (write)
Description:
- There are exactly 11 supported types:
EC_DT_BOOL,INT8,INT16,INT32,INT64,UINT8UINT16,UINT32,UINT64,REAL32,REAL64(multi-byte values little-endian)
- Anything outside the supported types returns
FALSE:EC_DT_BIT1..EC_DT_BIT8(includingEC_DT_BIT8— a bit string has different semantics fromEC_DT_UINT8, so it is deliberately not mapped)EC_DT_INT24/EC_DT_INT40/EC_DT_INT48/EC_DT_INT56(and the correspondingEC_DT_UINT24/EC_DT_UINT40/EC_DT_UINT48/EC_DT_UINT56)- strings (
EC_DT_VISIBLE_STRING/EC_DT_OCTET_STRING/EC_DT_UNICODE_STRING) EC_DT_TIME_OF_DAY/EC_DT_TIME_DIFFERENCE/EC_DT_DOMAIN/EC_DT_NONE
- It does not guess widths and does not silently read 1 byte.
The union has no run-time type tag, so the member must match type: to read EC_DT_INT16 use i16, to write EC_DT_REAL32 fill in f32.
The boolean member has bit0 semantics on read; on write it takes the boolean truth value, and what lands on the bus is still a whole byte 0x01 / 0x00.
Example:
ec_pdo_value_t v;
if (PDOItemReadValue(&item, EC_DT_INT32, &v))
printf("i32=%d\n", v.i32);
v.f32 = 12.5f;
if (!PDOItemWriteValue(&out_item, EC_DT_REAL32, &v))
printf("写入被拒\n"); /* Write rejected */
Related structures:
typedef union {
BOOL boolean; /* EC_DT_BOOL, bit0 semantics */
int8_t i8; /* EC_DT_INT8 */
uint8_t u8; /* EC_DT_UINT8 */
int16_t i16; /* EC_DT_INT16 */
uint16_t u16; /* EC_DT_UINT16 */
int32_t i32; /* EC_DT_INT32 */
uint32_t u32; /* EC_DT_UINT32 */
int64_t i64; /* EC_DT_INT64 */
uint64_t u64; /* EC_DT_UINT64 */
float f32; /* EC_DT_REAL32 */
double f64; /* EC_DT_REAL64 */
} ec_pdo_value_t;
Bit strings and variable-length types (ec_value_*)
Bit strings (EC_DT_BIT1..EC_DT_BIT8) have no fixed-width scalar accessor. Call ec_value_* directly on the element window, taking the width from
ec_value_type_bit_size (1..8):
int bits = ec_value_type_bit_size(EC_DT_BIT3); /* 3 */
uint64_t raw = 0;
if (ec_value_try_extract_u64(item.frame, item.size,
ec_pdo_item_bit_offset(&item), bits, &raw))
printf("bit3=%llu\n", (unsigned long long)raw);
Strings / EC_DT_DOMAIN are variable-length types: ec_value_type_bit_size returns -1 for them (not a usable width), and ec_value_* does not apply.
For these fields, take a whole-frame snapshot with CopySlaveInputPdo and parse the bytes yourself.
ec_pdo_item_bit_offset(&item) gives the bit offset of the element start (byte offset × 8); it performs no NULL check, so item must first have been obtained from
PDOArrayItem.
On the write side use ec_value_insert_u64 / ec_value_insert_i64 (EC_VALUE_OK means success); a bit-field write is a read-modify-write, and bits outside the field keep their values.
ec_value_* performs no direction check: it does not reject an input-side window for you. Use them only when writing to an output frame buffer (the frame taken by a versioned transaction), and the write must happen
before CommitSlaveOutputPdoVersioned.
PDO mapping and startup policy
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| Mapping enumeration | EnumerateDefaultPdoEx(mi, si, direction, out_indices, max_count, out_source) | int | read-only | assignment enumeration + fallback to the first entry in ESI document order + ETG default; returns the number of entries written |
| Mapping offsets | GetPdoOffsets(mi, si, direction, obj_indices, out_offsets, n_targets) | int | read-only | reads the mapping entries to compute byte offsets; returns the number of offsets produced |
| Mapping size | GetPdoMappingSize(mi, si, pdo_mapping_index) | int | read-only | total bytes of a single PDO mapping object, 0 = unknown |
| Mapping sizes | GetPdoAssignmentSizes(mi, si, direction, out_byte_sizes, max_count) | int | read-only | size of each PDO in the assignment, aligned with the enumeration positions |
| Probe policy | PdoProbeDecide(rx_ok, rx_count, tx_ok, tx_count) | int | read-only | 0x1C12 / 0x1C13 probe verdict: -1 keep probing / 1 configured / 0 confirmed empty |
| Startup policy | PdoResolveStartupPolicy(in, out) | int | read-only | Startup PDO Assignment / Mapping decision tree, 0 = success |
| Element layout | PdoBuildBoolOffsets(widths, is_bool, n, layout_size, out_offsets, max_out, out_count) | int | read-only | accumulates field widths to compute the byte offset of each boolean field |
| Encoding helper | DarraEcat_EcPdoCodec_BitsToBytes(total_bits) | int | read-only | converts an accumulated bit length into a PDO byte count (a partial byte counts as a full byte) |
| Encoding helper | DarraEcat_EcPdoCodec_MappingEntryBitLen(entry_le) | int | read-only | takes the Byte0 bit length from a PDO mapping entry |
The direction parameter is uniform: 0 = RxPDO (0x1C12, master → slave outputs), 1 = TxPDO (0x1C13, slave → master inputs).
The last two encoding helpers are provided in the C SDK only under the names DarraEcat_EcPdoCodec_BitsToBytes() / DarraEcat_EcPdoCodec_MappingEntryBitLen() (declared in darra_ethercat_shell.h, pulled in through ethercat.h); there are no short-name wrappers.
EnumerateDefaultPdoEx()
int EnumerateDefaultPdoEx(uint16_t master_index, uint16_t slave_index,
int direction, uint16_t* out_indices, int max_count,
int* out_source);
Enumerates the PDO indices currently in effect for the slave: first the assignment, then, when that is empty or fails, a fallback to the first entry in ESI document order, then the ETG default (0x1600 / 0x1A00); it never fails silently.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-baseddirection(int) —0= RxPDO,1= TxPDOout_indices(uint16_t*) — out parameter, receives the PDO indicesmax_count(int) — array capacityout_source(int*) — out parameter, where the index came from:0= assignment,1= first ESI entry,2= ETG default; may beNULL
Return value:
int— actual number of entries written (>= 1);-1on invalid arguments or when the SDK is not ready
Description: The difference from EnumerateDefaultPdo is that it reports the source and never returns 0 entries. Use it when a log or diagnostic must make clear whether this PDO index came from the assignment or from a fallback.
Example:
uint16_t pdos[16];
int source = -1;
int n = EnumerateDefaultPdoEx(m, 1, 0, pdos, 16, &source);
if (n < 0) {
printf("枚举失败\n"); /* Enumeration failed */
} else {
printf("RxPDO 共 %d 个,来源=%d\n", n, source); /* 0=assignment 1=first ESI entry 2=ETG default */
}
GetPdoOffsets()
int GetPdoOffsets(uint16_t master_index, uint16_t slave_index, int direction,
const uint16_t* obj_indices, int32_t* out_offsets, int n_targets);
Reads the mapping entries and computes the byte offset of these objects in the process image for that direction.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-baseddirection(int) —0= RxPDO,1= TxPDOobj_indices(const uint16_t*) — array of object indices to locateout_offsets(int32_t*) — out parameter, byte offsets corresponding one for one toobj_indicesn_targets(int) — number of targets
Return value:
int— number of offsets produced (>= 0);-1on invalid arguments or when the SDK is not ready
Description:
out_offsets[i]= the matched object's bit width divided by 8, with the remainder discarded.- Entries that do not match, or that come after a failed read, are written as
-1; offsets before the failure point remain valid and can be used safely. - The first failed read stops accumulation for that direction immediately; it does not skip the failed entry and keep going — otherwise every later offset would be shifted.
Example:
uint16_t objs[3] = { 0x6040, 0x607A, 0x6060 };
int32_t offs[3] = { 0 };
int found = GetPdoOffsets(m, 1, 0, objs, offs, 3);
if (found >= 0) {
/* found is the number of matches; offs still follows the positions of obj_indices, -1 for a miss */
for (int i = 0; i < 3; i++) {
if (offs[i] < 0)
printf("0x%04X 未能定位(未命中或读失败点之后)\n", objs[i]); /* 0x%04X could not be located (no hit, or beyond the read-failure point) */
else
printf("0x%04X 偏移 %d\n", objs[i], offs[i]); /* 0x%04X offset %d */
}
}
GetPdoMappingSize()
int GetPdoMappingSize(uint16_t master_index, uint16_t slave_index,
uint16_t pdo_mapping_index);
The total byte count of a single PDO mapping object (such as 0x1600 / 0x1A00).
Return value:
int— byte count;0= unknown (read failed or SDK not ready)
Description: Any failed read returns 0; there is no partial accumulation — unknown is unknown, do not read 0 as "this PDO is empty". When the SDK is not ready it also returns 0; to test whether the SDK is ready check DarraEcat_ShellReady().
GetPdoAssignmentSizes()
int GetPdoAssignmentSizes(uint16_t master_index, uint16_t slave_index, int direction,
int32_t* out_byte_sizes, int max_count);
The size list of each PDO in the assignment (0x1C12 / 0x1C13), with positions aligned one for one with the enumeration order of EnumerateDefaultPdoEx.
Parameters:
master_index(uint16_t) — master index, 1-basedslave_index(uint16_t) — slave index, 1-baseddirection(int) —0= RxPDO,1= TxPDOout_byte_sizes(int32_t*) — out parameter, byte count of each PDOmax_count(int) — array capacity
Return value:
int— number of entries written (>= 0);-1on invalid arguments or when the assignment enumeration fails
Description: Entries are written one by one in the enumeration order of the assignment, skipping empty slots whose value is 0; an entry that cannot be read is written as 0 = unknown and is not dropped — so out_byte_sizes stays aligned with the enumeration entries that have content. When the SDK is not ready it returns 0 (the same shape as "no entries"); to test whether the SDK is ready check DarraEcat_ShellReady(). When you need enumeration with the ESI / ETG fallback, get the indices with EnumerateDefaultPdoEx first, then call GetPdoMappingSize for each of them.
PdoProbeDecide()
int PdoProbeDecide(int rx_ok, int rx_count, int tx_ok, int tx_count);
The conservative verdict of the 0x1C12 / 0x1C13 probe (a business value, not an error code).
Parameters:
rx_ok(int) — whether 0x1C12 was read (1= success,0= not successful)rx_count(int) — number of entries read from 0x1C12tx_ok(int) — 0x1C13 read state: pass-1to mean not probed yet, and the function returns-1so the caller keeps probing;1= success,0= not successfultx_count(int) — number of entries read from 0x1C13
Return value:
int—-1= keep probing tx;1= treat as configured (trust the EEPROM);0= confirmed empty
Description: This entry has no distinguishable not-ready sentinel: -1 can be either a business verdict or an SDK that is not loaded. To determine the SDK state you must check DarraEcat_ShellReady(); do not use "return value less than 0" to decide whether the SDK is ready. Except for the "tx not probed yet" branch, any uncertain reading in either direction is conservatively treated as "configured", to avoid injecting ESI presets by mistake.
PdoResolveStartupPolicy()
int PdoResolveStartupPolicy(const ec_pdo_startup_policy_in_t* in,
ec_pdo_startup_policy_out_t* out);
The Startup PDO Assignment / Mapping decision tree: given the slave and the ESI conditions, it decides which Startup items to write this time, and whether to take the full generation path, return empty, generate AltSm and then return, or only Mapping.
Return value:
int—0= success;-1= invalid arguments or SDK not ready
Related structures:
typedef struct ec_pdo_startup_policy_in {
uint8_t slave_has_own_pdo, esi_allow_assignment, esi_allow_configuration,
all_pdo_fixed, has_init_cmd, has_alt_sm_mapping,
init_cmd_requires_explicit, probe_enabled;
} ec_pdo_startup_policy_in_t;
typedef struct ec_pdo_startup_policy_out {
uint8_t action; /* 0=full generation 1=return empty 2=generate AltSm then return 3=Mapping only */
uint8_t write_assignment; /* whether to write 0x1C12 / 0x1C13 */
uint8_t write_configuration; /* whether to write the 0x16xx / 0x1Axx mappings */
uint8_t resolved_valid; /* whether resolved_value is valid */
uint8_t resolved_value;
} ec_pdo_startup_policy_out_t;
Description: Both structs follow the public ABI layout, and their field order and types must not change; this is the single decision point for "given the conditions found, which Startup items get written" — do not copy the branching again in any language layer.
PdoBuildBoolOffsets()
int PdoBuildBoolOffsets(const uint32_t* widths, const uint8_t* is_bool, int n,
uint32_t layout_size, uint32_t* out_offsets,
int max_out, int* out_count);
Accumulates the field widths in declaration order and computes the byte offset of each boolean field within the layout.
Parameters:
widths(const uint32_t*) — byte width of each leaf field, in declaration orderis_bool(const uint8_t*) — whether the corresponding entry is a boolean fieldn(int) — number of fieldslayout_size(uint32_t) — total layout width in bytesout_offsets(uint32_t*) — out parameter, writes the byte offset of each boolean field in order of appearance (only boolean entries, not one per entry)max_out(int) — output capacityout_count(int*) — out parameter, number of boolean fields actually written
Return value:
int—0= success;-1= invalid arguments (including SDK not ready);-2= the accumulated total width does not matchlayout_size;-3= output capacity too small
Description: With no boolean fields, out_count = 0 and it returns 0. When the total width does not match (the struct has padding or uses explicit offsets) it returns -2 — in that case it neither guesses offsets nor continues with wrong ones; better to have the caller switch to a tightly packed layout.
DarraEcat_EcPdoCodec_BitsToBytes()
int DarraEcat_EcPdoCodec_BitsToBytes(int total_bits);
Converts an accumulated bit length into a PDO byte count, counting any partial byte as a full byte; total_bits <= 0 returns 0.
Return value:
int— byte count;-1when the SDK is not ready (normal values are>= 0, so the two are distinguishable)
DarraEcat_EcPdoCodec_MappingEntryBitLen()
int DarraEcat_EcPdoCodec_MappingEntryBitLen(uint32_t entry_le);
Decodes one 32-bit little-endian PDO mapping entry into a bit length: Byte0 is the BitLength.
Return value:
int— bit length0..255;-1when the SDK is not ready
Full example
#include <stdio.h>
#include <stdint.h>
#include <ethercat.h>
#pragma pack(push, 1)
typedef struct { uint16_t status_word; int32_t actual_position; } in_pdo_t;
typedef struct { uint16_t control_word; int32_t target_position; } out_pdo_t;
#pragma pack(pop)
int main(void)
{
/* one-step JSON initialization: load + enter OP */
uint16_t m = EcInitFromFile("C:\\EtherCAT\\MyProject.json");
if (m == 0) return 1;
/* ① zero-copy hot path: map the packed struct onto the process image */
int32_t out_size = 0, in_size = 0;
uint8_t *out_ptr = NULL, *in_ptr = NULL;
if (!ec_pdo_io_is_ok(GetIO(m, 1, &out_size, &out_ptr, &in_size, &in_ptr)))
return 1; /* not in OP, or the process image is unavailable */
if ((size_t)in_size < sizeof(in_pdo_t) || (size_t)out_size < sizeof(out_pdo_t))
return 1; /* struct larger than the IO area: it would overrun another slave */
in_pdo_t *in = (in_pdo_t *)in_ptr;
out_pdo_t *out = (out_pdo_t *)out_ptr;
out->control_word = 0x000F; /* write: sent in the next cycle */
out->target_position = in->actual_position + 1000;
printf("status=0x%04X pos=%d\n", in->status_word, in->actual_position);
/* ② element view: take one input snapshot, then read one fixed-width scalar by offset */
uint8_t frame[64];
uint32_t copied = 0, required = 0;
uint8_t st = CopySlaveInputPdo(m, 1, frame, (uint32_t)sizeof frame, &copied, &required);
if (ec_pdo_io_is_ok(st)) {
ec_pdo_array_t arr;
ec_pdo_data_item_t item;
uint16_t sw = 0;
BOOL ready = FALSE;
if (PDOArrayFromFrame(frame, (int32_t)copied, TRUE, &arr) /* a snapshot frame is input side: read-only */
&& PDOArrayItem(&arr, 0, &item)) {
if (PDOItemReadUInt16(&item, &sw)) /* little-endian, 2 bytes */
printf("快照 status=0x%04X\n", sw); /* Snapshot status=0x%04X */
if (PDOItemReadBit(&item, 0, &ready)) /* bit0 of the same byte */
printf("ready=%d\n", ready);
}
/* to write outputs partially by offset, use a versioned transaction; see usage example ③ */
} else if (ec_pdo_io_is_buffer_too_small(st)) {
printf("输入帧 %u 字节,缓冲区扩容后重试\n", required); /* Input frame %u bytes, retry after growing the buffer */
}
getchar();
EcClose(m); /* one-step close: Stop + Dispose */
return 0;
}
PDO mapping information and statistics monitoring
This section complements "PDO mapping and startup policy": GetPDOMapping() returns the process image size for one direction, while the GetPDOStats() family reads, resets and switches runtime statistics. They are not the same layer as GetPdoMappingSize() (the byte count of a single mapping object) or GetPdoOffsets() (an object's offset inside the process image), and the two must not be substituted for each other.
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| PDO mapping | GetPDOMapping(mi, si, pdo_type, mapping_buffer, buffer_size, mapping_count) | BOOL | read-only | Returns the number of bytes needed by the process image in the given direction; it does not return mapping entries |
| PDO statistics | GetPDOStats(mi, si) | void* (ec_pdo_stats_t) | read-only | Returns a pointer to this slave's internal statistics entry; no release needed |
ResetPDOStats(mi, si) | void | write-only | Clears this slave's statistics | |
| PDO monitoring | EnablePDOMonitoring(enable) | void | write-only | Process-wide switch for statistics collection |
IsPDOMonitoringEnabled() | BOOL | read-only | Queries the current switch state |
GetPDOMapping()
BOOL GetPDOMapping(uint16_t master_index, uint16_t slave_index, uint16_t pdo_type,
void* mapping_buffer, uint32_t buffer_size,
uint32_t* mapping_count);
Parameters:
master_index/slave_index(uint16_t) — master / slave index (1-based)pdo_type(uint16_t) — direction:0= input (TxPDO),1= output (RxPDO). Note that this is the opposite ofdirectioninGetPdoAssignmentSizes()(there0= RxPDO and1= TxPDO); do not mix them upmapping_buffer(void*) — required output buffer, not an array of mapping entries: whenbuffer_size >= sizeof(uint32_t), the function writes the required byte count (uint32_t) at the start of the bufferbuffer_size(uint32_t) — buffer capacity in bytesmapping_count(uint32_t*) — output parameter: the process image byte count for that direction, not the number of mapping entries
Return value:
BOOL—TRUE= the call completed; when the buffer is too small it still returnsTRUE, with the required byte count inmapping_count, and the caller retries after growing the bufferFALSE= invalid parameters (mapping_buffer/mapping_countisNULL, index out of range) or the process image is not readable- This function does not scan mapping entries and does not return an entry list. For entry details (index, subindex, bit length), read the object dictionary through CoE: first read the assignment in
0x1C12/0x1C13, then the mapping in0x16xx/0x1Axx - It also does not copy process data; process image reads and writes still go through
GetIO()/CopySlaveInputPdo()and similar entry points
GetPDOStats()
void* GetPDOStats(uint16_t master_index, uint16_t slave_index);
Return value:
- A pointer to this slave's internal statistics entry (
ec_pdo_stats_t); borrowed read-only, no release needed — do not callFreeMemory()/free() - Returns
NULLwhen the index is out of range
Statistics fields (ec_pdo_stats_t):
ReadCount/WriteCount— cumulative read / write countErrorCount— cumulative error countTotalBytesRead/TotalBytesWritten— cumulative read / written byte countLastCycleTimeNs/MinCycleTimeNs/MaxCycleTimeNs/AvgCycleTimeNs— most recent / minimum / maximum / average cycle time (nanoseconds)- Counters accumulate from the last
ResetPDOStats()(or from the clear performed when monitoring is turned off)
ResetPDOStats()
void ResetPDOStats(uint16_t master_index, uint16_t slave_index);
Clears this slave's statistics entry and returns nothing. It does not change the monitoring switch state and does not affect PDO transmission; after the clear, counting restarts from 0.
EnablePDOMonitoring() / IsPDOMonitoringEnabled()
void EnablePDOMonitoring(BOOL enable);
BOOL IsPDOMonitoringEnabled(void);
enable(BOOL) —TRUEturns statistics collection on,FALSEturns it off- The switch is process-wide and does not distinguish masters / slaves; every slave's statistics in the same process share it
- It is off by default; you must turn it on before
GetPDOStats()has data. While it is off, read / write counts and cycle times are not updated - Turning it off (
FALSE) clears the statistics table, so counting starts from 0 again when it is turned back on IsPDOMonitoringEnabled()returns the current state:TRUE= enabled
Example:
#include <ethercat.h>
/* ① Ask for the required byte count first: the buffer must be at least 4 bytes and the function writes the same value at the start of the buffer*/
uint32_t probe = 0, required = 0;
if (!GetPDOMapping(master, 1, 0, &probe, sizeof probe, &required)) {
printf("过程映像尺寸读取失败\n"); /* Process image size read failed */
} else {
/* ② Grow to the required size and fetch again*/
uint32_t* buf = (uint32_t*)malloc(required ? required : sizeof(uint32_t));
uint32_t got = 0;
if (buf != NULL && GetPDOMapping(master, 1, 0, buf, required, &got))
printf("输入过程映像需要 %u 字节(缓冲首 4 字节 = %u)\n", got, *buf); /* Input process image needs %u bytes (first 4 bytes of the buffer = %u) */
free(buf);
}
/* ③ Turn monitoring on, let the PDO cycle run for a while, then read the statistics*/
EnablePDOMonitoring(TRUE);
ec_pdo_stats_t* stats = (ec_pdo_stats_t*)GetPDOStats(master, 1);
if (stats != NULL) {
printf("read=%u write=%u err=%u avg=%llu ns\n",
stats->ReadCount, stats->WriteCount, stats->ErrorCount,
(unsigned long long)stats->AvgCycleTimeNs);
}
/* ④ Reset that slave's statistics*/
ResetPDOStats(master, 1);