*注意:这是来自 Zynq-7000。我相信大体上是一样的。
假设您使用的是设备树,这是一个示例条目(在设备树中):
gpio-device {
compatible = "gpio-control";
gpios = <&gpio0 54 0>; //(Add 32 to get the actual pin number. This is GPIO 86)
};
并且您需要在驱动程序中声明您与设备树条目兼容(查看其他驱动程序以了解该行的放置位置):
.compatible = "gpio-control"
在您的驱动程序中,包含#include <linux/gpio.h> 并从设备树中读取引脚:
struct device_node *np = pdev->dev.of_node;
int pin;
pin = of_get_gpio(np, 0);
if (pin < 0) {
pr_err("failed to get GPIO from device tree\n");
return -1;
}
请求使用GPIO:
int ret = gpio_request(pin, "Some name"); //Name it whatever you want
并设置它的方向:
int ret = gpio_direction_output(pin, 0); //The second parameter is the initial value. 0 is low, 1 is high.
然后,像这样设置值:
gpio_set_value(pin, 1);
输入:
ret = gpio_direction_input(pin);
value = gpio_get_value(pin);
使用完后释放 GPIO(包括出错时!):
gpio_free(pin);
归根结底,一个好方法是在内核周围grep 找到执行您想要的驱动程序。事实上,grep -r gpio <<kernel_source>> 会在这个答案中告诉你一切等等。