Let’s read one pin, as same as the previous examples we assume we do not know if there is a switch/button connected to our pin (but a button is there), so we configure the pin as input with a pull-up, and then use gpio_pin_get
function to read the pin status every 500ms.
main.c
/* Include libraries */
#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 GPIO2_NODE DT_NODELABEL( gpio2 )
int main( void )
{
/* Get the device descriptor for port 2 */
const struct device *gpio2 = DEVICE_DT_GET( GPIO2_NODE );
/* Configure p13 as output with an active pull-up */
gpio_pin_configure( gpio2, 13, ( GPIO_INPUT | GPIO_PULL_UP );
while(1)
{
/* read the pin every 500ms */
int state = gpio_pin_get( gpio2, 13 );
printk( "Pin state: %d \n", state );
/* 500ms Delay */
k_msleep( 500 );
}
return 0;
}
prj.conf
# Disable optimizations
CONFIG_NO_OPTIMIZATIONS=y
# Include GPIO driver in system config ( Kconfig )
CONFIG_GPIO=y