Skip to content

Commit 21b8eb9

Browse files
committed
include: zephyr: devicetree: Add DT_CHILD_BY_IDX
Adds `DT_CHILD_BY_IDX` to get the child elements of a node by index. Signed-off-by: TOKITA Hiroshi <[email protected]>
1 parent 05b77ec commit 21b8eb9

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

include/zephyr/devicetree.h

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,44 @@
435435
*/
436436
#define DT_CHILD(node_id, child) UTIL_CAT(node_id, DT_S_PREFIX(child))
437437

438+
/**
439+
* @brief Get a child node by index
440+
*
441+
* This macro retrieves a child node of a specified node by its
442+
* index. The index corresponds to the order in which the child nodes
443+
* are defined in the Devicetree source.
444+
*
445+
* Example devicetree fragment:
446+
*
447+
* @code{.dts}
448+
* / {
449+
* parent_node {
450+
* first_child {
451+
* reg = <0>;
452+
* };
453+
* second_child {
454+
* reg = <1>;
455+
* };
456+
* };
457+
* };
458+
* @endcode
459+
*
460+
* Example usage:
461+
*
462+
* @code{.c}
463+
* DT_CHILD_BY_IDX(DT_NODELABEL(parent_node), 0) // "first_child"
464+
* DT_CHILD_BY_IDX(DT_NODELABEL(parent_node), 1) // "second_child"
465+
* @endcode
466+
*
467+
* @param node_id The identifier of the parent node. This can be obtained
468+
* using macros like DT_NODELABEL(), DT_PATH(), or similar.
469+
* @param idx The index of the child node to retrieve. Must be within
470+
* the range of 0 to DT_CHILD_NUM(node_id) - 1.
471+
*
472+
* @return The identifier of the child node at the specified index.
473+
*/
474+
#define DT_CHILD_BY_IDX(node_id, idx) UTIL_CAT(UTIL_CAT(node_id, _CHILD_IDX_), idx)
475+
438476
/**
439477
* @brief Get a node identifier for a status `okay` node with a compatible
440478
*

scripts/dts/gen_defines.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -478,10 +478,12 @@ def write_children(node: edtlib.Node) -> None:
478478
out_dt_define(f"{node.z_path_id}_CHILD_NUM", len(node.children))
479479

480480
ok_nodes_num = 0
481-
for child in node.children.values():
481+
for i, child in enumerate(node.children.values()):
482482
if child.status == "okay":
483483
ok_nodes_num = ok_nodes_num + 1
484484

485+
out_dt_define(f"{node.z_path_id}_CHILD_IDX_{i}", f"DT_{child.z_path_id}")
486+
485487
out_dt_define(f"{node.z_path_id}_CHILD_NUM_STATUS_OKAY", ok_nodes_num)
486488

487489
out_dt_define(f"{node.z_path_id}_FOREACH_CHILD(fn)",

0 commit comments

Comments
 (0)