Write a couple of values in port 0 (from pin 0 to pin 7), we use the function gpio_port_set_bits
to write a value of '1' on those selected pins, notice that before writing a new value we need to clear the previous one using gpio_port_clear_bits
function. there is no function to configure an entire port or certain selected pins (but this can be done using the device tree), so we do it one by one.
Note: on We are assuming you are using a board with at least an 8 bit port available
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 0 */
#define PORT_NODE DT_NODELABEL( gpio0 )
int main( void )
{
/* Get the port 0 reference */
const struct device * gpio = DEVICE_DT_GET( PORT_NODE );
/* you can ask to zephyr if the device (port 0) it is ready to be use */
if( device_is_ready( gpio ) == false ) {
printk("gpio0 device is not ready\n");
while(1u);
}
/* Set pins 0 - 4 from port 0 port as output, one by one */
for(uint8_t pin = 0; pin < 8; pin++){
gpio_pin_configure( gpio, pin, GPIO_OUTPUT );
}
while(1)
{
/* Write the value 0x15 on port 0 */
gpio_port_clear_bits( gpio, 0xFF );
gpio_port_set_bits( gpio, 0x15 );
k_msleep( 300 );
/* Write the value 0x0A on port 0 */
gpio_port_clear_bits( gpio, 0xFF );
gpio_port_set_bits( gpio, 0x0A );
k_msleep( 300 );
}
return 0;
}
prj.conf
# Disable optimizations
CONFIG_NO_OPTIMIZATIONS=y
# Include GPIO driver in system config ( Kconfig )
CONFIG_GPIO=y