Skip to content

Commit 2b365c5

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 642e97d commit 2b365c5

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
@@ -425,6 +425,44 @@
425425
*/
426426
#define DT_CHILD(node_id, child) UTIL_CAT(node_id, DT_S_PREFIX(child))
427427

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

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)