如何将39号gpio口写进驱动,并设置为输出态,并在输出时拉高?

问题遇到的现象和发生背景

如何将39号gpio口写进驱动,并设置为输出态,并在输出时拉高?

遇到的现象和发生背景,请写出第一个错误信息
用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%
运行结果及详细报错内容
我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%
我想要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”

ChatGPT尝试为您解答,仅供参考
首先,您需要确保您有足够的权限来访问和操作系统的GPIO口。这通常意味着您需要以root用户身份运行您的程序。

然后,您需要包含相应的头文件,例如:

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

接下来,您需要打开GPIO口并设置为输出模式:

int fd;
fd = open("/sys/class/gpio/export", O_WRONLY);
if (fd == -1) {
  perror("Unable to open /sys/class/gpio/export");
  exit(1);
}

if (write(fd, "39", 2) == -1) {
  perror("Unable to write to /sys/class/gpio/export");
  exit(1);
}

close(fd);

fd = open("/sys/class/gpio/gpio39/direction", O_WRONLY);
if (fd == -1) {
  perror("Unable to open /sys/class/gpio/gpio39/direction");
  exit(1);
}

if (write(fd, "out", 3) == -1) {
  perror("Unable to write to /sys/class/gpio/gpio39/direction");
  exit(1);
}

close(fd);

最后,您可以使用以下代码将GPIO口拉高:

fd = open("/sys/class/gpio/gpio39/value", O_WRONLY);
if (fd == -1) {
  perror("Unable to open /sys/class/gpio/gpio39/value");
  exit(1);
}

if (write(fd, "1", 1) == -1) {
  perror("Unable to write to /sys/class/gpio/gpio39/value");
  exit(1);
}

close(fd);

注意:在写入“1”后,GPIO口将保持拉高状态,直到您将其写为“0”。

最后,当您完成使用GPIO口时,请记得关闭它:

fd = open("/sys/class/gpio/unexport", O_WRONLY);
if (fd == -1) {
  perror("Unable to open /sys/class/gpio/unexport");
  exit(1);
}

if (write(fd, "39", 2) == -1) {
  perror("Unable to write to /sys/class/gpio/unexport");
  exit(1);
}

close(fd);

这将释放系统资源并确保您不会意外影响其他程序使用GPIO口。


在设备树中添加 gpio39 口的方法如下:

1.在设备树中添加一个新节点,表示 gpio39 口。这可以通过在设备树文件中添加一行类似如下的代码实现:

gpio39 {
        compatible = "gpio-controller";
        #gpio-cells = <2>;
        gpio-controller;
        reg = <0x39 0x1>;
    };

其中,compatible 属性表示 gpio39 口所使用的 gpio 驱动的名称,reg 属性表示 gpio39 口的地址。


2.在设备树文件中添加一个新的设备,表示使用 gpio39 口的设备。这可以通过在设备树文件中添加一行类似如下的代码实现:

my_device {
        compatible = "my_device_driver";
        gpios = <&gpio39 0>;
    };

其中,compatible 属性表示使用该 gpio39 口的设备所使用的驱动的名称,gpios 属性表示使用的 gpio 口的标识符。