How to add constants to a devicetree overlay?

Viewed 283

I'd like to define some constants in a devicetree overlay. For example: To give gpio pin 9 the name led-blue, I've added the following to the devicetree overlay:

/ {
    gpio_pin_names {
        led-blue = < 9 >;
    };
};

This adds the following to zephyr.dts:

gpio_pin_names {
    led-blue = < 0x9 >;
};

However, nothing shows up at devicetree_unfixed.h, making it a little difficult to read the value in code...

What's the proper way to add a constant to a devicetree overlay? And how do you read the value in code?

1 Answers

In your boards device tree:

/dts-v1/;
#include <nordic/nrf51822_qfaa.dtsi>

/ {
    model = "nRF51test";
    compatible = "nrf51test";

    chosen {
        zephyr,sram = &sram0;
        zephyr,flash = &flash0;
        zephyr,flash-controller = &flash_controller;
    };

    leds {
        compatible = "gpio-leds";
        ledblue: ledblue {
            gpios = <&gpio0 23 0>;
            label = "Blue LED";
        };
    };

    aliases {
        ledblue = &ledblue;
    };
};

&gpiote {
    status = "okay";
};

&gpio0 {
    status = "okay";
};

Then in your code to use ledblue:

//ledblue config
#define LEDBLUE_NODE DT_ALIAS(ledblue)
#define LEDBLUE      DT_GPIO_LABEL(LEDBLUE_NODE, gpios)
#define LEDBLUEPIN   DT_GPIO_PIN(LEDBLUE_NODE, gpios)
#define FLAGS        DT_GPIO_FLAGS(LEDBLUE_NODE, gpios)


void main(void)
{
    const struct device *dev;
    dev = device_get_binding(LEDBLUE);
    int ret;
    ret = gpio_pin_configure(dev, LEDBLUEPIN, GPIO_OUTPUT_ACTIVE | FLAGS);

    bool led_is_on = true;
    while (true) {
        //flash blue led
        gpio_pin_set(dev, LEDBLUEPIN, (int)led_is_on);
        led_is_on = !led_is_on;
        k_msleep(500);
    }
}

EDIT: If you want to ignore the device tree and do everything in main.c, you can use less code - although if the board switches you will need to change the main.c code to reflect this (in this example no LED would be declared in the device tree):

#define BLUE_LED_PIN 23

void main(void)
{
    const struct device *devGPIO;
    int ret;
    devGPIO = device_get_binding("GPIO0");
    ret = gpio_pin_configure(devGPIO, BLUE_LED_PIN, GPIO_OUTPUT_ACTIVE);
    gpio_pin_set(devGPIO, BLUE_LED_PIN, 1); //1 for on, 0 for off
}
Related