Linux內核LED驅動
Linux 內核集成了LED驅動,採用platform
框架,我們只需要在編譯內核時選擇LED驅動,在設備樹文件中添加LED節點即可。
內核使能LED驅動
- 進入Linux內核文件夾,輸入如下命令進入配置菜單:
$ make menuconfig
- 按照如下路徑打開LED驅動配置項:
->Device Drivers
->LED Support(NEW_LEDS[=y])
->LED Support for GPIO connected LEDs
按Y使能。保存退出,然後編譯內核。
LED驅動源碼分析
在上面使能LED驅動後,drivers/leds/leds-gpio.c
就會被編譯。
在leds-gpio.c
中有設備匹配表如下:
static const struct of_device_id of_gpio_leds_match[] = {
{ .compatible = "gpio-leds", },
{ },
};
......
static struct platform_driver gpio_led_driver = {
.probe = gpio_led_probe,
.remove = gpio_led_remove,
.driver = {
.name = "leds-gpio",
.of_match_table = of_gpio_leds_match,
},
};
module_platform_driver(gpio_led_driver);
- 因此設備樹中的
compatible
屬性爲gpio-leds
的節點都會被leds-gpio.c
驅動匹配。 - 在
gpio_led_driver
中name
爲leds-gpio
,因此在註冊驅動之後,/sys/bus/platform/drivers/
下會有leds-gpio
驅動。 - 其中
module_platform_driver(gpio_led_driver);
用於註冊驅動。其定義在include/linux/platform_device.h
中,如下:
#define module_platform_driver(__platform_driver) \
module_driver(__platform_driver, platform_driver_register, \
platform_driver_unregister)
可以看出是一個宏,依賴於module_driver()
,module_driver()
定義在include/linux/device.h
中,如下:
#define module_driver(__driver, __register, __unregister, ...) \
static int __init __driver##_init(void) \
{ \
return __register(&(__driver) , ##__VA_ARGS__); \
} \
module_init(__driver##_init); \
static void __exit __driver##_exit(void) \
{ \
__unregister(&(__driver) , ##__VA_ARGS__); \
} \
module_exit(__driver##_exit);
由此可知,將module_platform_driver(gpio_led_driver);
展開後爲:
static int __init gpio_led_driver_init(void)
{
return platform_driver_register (&(gpio_led_driver));
}
module_init(gpio_led_driver_init);
static void __exit gpio_led_driver_exit(void)
{
platform_driver_unregister (&(gpio_led_driver) );
}
module_exit(gpio_led_driver_exit);
即爲platform驅動的註冊和刪除。
設備樹節點編寫
- 創建dtsleds 節點表示LED設備,節點中可以有多個led子節點
- dtsleds 節點的
compatible
必須是gpio-leds
- 設置
label
屬性,這個將設置爲led的名字 - 每個子節點必須設置
gpios
屬性,表明其GPIO引腳 linux,default-trigger
屬性爲LED默認功能配置,可選項有:
backlight : LED作爲背光
default-on : LED燈默認打開
default-off : LED燈默認關閉
heartbeat : LED作爲心跳燈,作爲系統運行提示燈
ide-disk : LED作硬盤活動指示燈
timer : LED週期性閃爍,由定時器驅動,閃爍頻率可以修改。
default-state
設置默認狀態,可選項有: on off keep
設備樹LED節點
添加dtsled節點如下:
dtsleds {
compatible = "gpio-leds";
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_light>;
led_red {
label = "red";
gpios = <&gpio1 4 GPIO_ACTIVE_LOW>;
default-state = "on";
linux,default-trigger = "timer";
};
};
編譯設備樹,重啓。
設備操作
- 修改完設備樹之後,在
/sys/devices/platform/
下存在dtsles設備節點,即設備樹節點添加成功。 - 進入
/sys/class/leds
目錄中,發現有red節點,即led驅動匹配成功,通過如下指令即可調整led狀態:
echo 1 > /sys/class/leds/red/brightness //打開 LED0
echo 0 > /sys/class/leds/red/brightness //關閉 LED0