使用c++libgpiod库,如何将gpio行设置为输出,并使用set_value()函数操作单行

Using c++ libgpiod library, how can I set gpio lines to be outputs and manipulate single lines with set_value() function?

本文关键字:set value 单行 操作 函数 输出 c++libgpiod gpio 设置 使用      更新时间:2023-10-16

我刚开始使用libgpiod库的c++绑定,设置gpios时遇到问题。我知道,我可以创建值的长向量,并一次将其应用于所有值,但我希望能够设置它们的方向,并分别控制它们。我该怎么做?

我尝试的是:

第一:同时应用所有值的工作代码:

#include <gpiod.hpp>
int main(int argc, char **argv)
{
::gpiod::chip chip("gpiochip0");
auto lines = chip.get_all_lines();
::gpiod::line_request requestOutputs = {
argv[0],
::gpiod::line_request::DIRECTION_OUTPUT,
0
};
int value_to_be_set = 0xAAAAAAA ; //example value
::std::vector<int> values;
for (int i = 0; i < 32; i++)
{
values.push_back((value_to_be_set >> i) & 1UL);
}
lines.request(requestOutputs, values);
lines.release();
return EXIT_SUCCESS;
}

第二,我想要的方法:

#include <gpiod.hpp>
int main(int argc, char **argv)
{
::gpiod::chip chip("gpiochip0");
auto lines = chip.get_all_lines();
::gpiod::line_request requestOutputs = {
argv[0],
::gpiod::line_request::DIRECTION_OUTPUT,
0
};
lines.request(requestOutputs);
int value_to_be_set = 0xAAAAAAA; //example value
for (int i = 0; i < 32; i++)
{
// This does not set value :(
lines.get(i).set_value((value_to_be_set >> i) & 1UL);
}
lines.release();
return EXIT_SUCCESS;
}

我也找不到一个简单的C++示例来使用最新的Raspberry PI库切换单个GPIO线。

下面有一个多行示例,但这不是最初询问的内容:https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/bindings/cxx

下面是一个示例,它将导致GPIO17先变高,然后变低,以创建单线输出脉冲。

// Use gpio drivers to toggle a single GPIO
// line on Raspberry Pi
// Use following commands to install prerequisites and build
// sudo apt install gpiod
// sudo apt install libgpiod-dev
// g++ -Wall -o gpio gpip.cpp -lgpiodcxx
#include <iostream>
#include <gpiod.hpp>
#include <unistd.h>

int main(void)
{ 
::gpiod::chip chip("gpiochip0");

auto line = chip.get_line(17);  // GPIO17
line.request({"example", gpiod::line_request::DIRECTION_OUTPUT, 0},1);  

sleep(0.1);

line.set_value(0);
line.release();
}

也不要忘记使用标志-lgpiodcxx(对于c++(或-lgpiod(对于c(进行构建