GPIO pin initialization can be carried out by the internal Zephyr GPIO driver, we just need to indicate in the device tree using hogs which is basically a child node for each port where we can set the pin as input or output
main.c
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
/* get the node identifier from its label, in this case will be gpio@50400 for port 2 */
#define LED_NODE DT_NODELABEL( gpio2 )
int main( void )
{
/* From the default devicetree get the gpio0 reference */
const struct device * gpio2 = DEVICE_DT_GET( LED_NODE );
/* No need to call any initialization function */
while(1)
{
/* Toggle pin 9 from port 2 using a port function */
gpio_pin_toggle( gpio2, 9 );
/* 300ms Delay */
k_msleep( 300 );
}
return 0;
}
app.overlay
/* phandle for gpio2 port */
&gpio2 {
/* Declare an internal node name led-0 for pin 9 */
led_0: led-0{
gpio-hog;
/* config pin 9 as */
gpios = <9 GPIO_ACTIVE_HIGH>;
/* Set pin as output with init state as high level */
output-high;
};
};
prj.conf
# Disable optimizations
CONFIG_NO_OPTIMIZATIONS=y
# Include GPIO drivers in system config (KCONFIG)
CONFIG_GPIO=y
# Option to init pins using the DTC
CONFIG_GPIO_HOGS=y