如何在树莓派4上通过libgpiod V1设置GPIO内部上拉电阻?
问题:树莓派4使用libgpiod V1设置GPIO内部上拉电阻编译报错
我正在使用树莓派4,希望将GPIO线路设置为使用内部PULL_UP(树莓派8号以上的线路默认均为pull_down)。使用C++和libgpiod V1编写的代码如下:
try { gpiod::chip chip("gpiochip0"); gpiod::line_bulk lines; const std::vector<io_gpio_t> offsets = { {1, 21}, {2, 26}, {3, 16}, {4, 19}}; for (io_gpio_t offset : offsets) { auto line = chip.get_line(offset.gpio_line); line.set_bias(gpiod::line::bias::pull_up); // <<---- ERROR HERE!!!! line.request({"io", gpiod::line_request::EVENT_BOTH_EDGES, 100000}); lines.append(line); } while (true) { gpiod::line_bulk changed_lines = lines.event_wait(std::chrono::seconds(10)); for (gpiod::line line : changed_lines) { auto event = line.event_read(); int offset = line.offset(); process_digital_in(offset, event); // Process event } } } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << std::endl; }
但libgpiod 1.6版本似乎不支持set_bias方法,编译报错如下:
src/IO.cpp:79:18: error: ‘class gpiod::line’ has no member named ‘set_bias’; did you mean ‘set_flags’? 79 | line.set_bias(gpiod::line::bias::pull_up); | ^~~~~~~~ | set_flags src/IO.cpp:79:40: error: ‘gpiod::line::bias’ is not a class, namespace, or enumeration 79 | line.set_bias(gpiod::line::bias::pull_up); | ^~~~
编译器提示使用set_flags,但找不到相关文档,请问如何通过代码正确设置输入线路使用内部上拉电阻?
解决方法
libgpiod 1.x系列(包括1.6版本)确实没有set_bias()方法,这个API是在libgpiod 2.x版本才新增的。要在1.6中设置GPIO内部上拉电阻,有两种可行方式:
方式1:在请求线路时指定偏置标志
在调用line.request()时,通过请求配置的flags参数添加GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_UP标志,这是推荐的方式,因为线路请求时会一次性完成配置:
try { gpiod::chip chip("gpiochip0"); gpiod::line_bulk lines; const std::vector<io_gpio_t> offsets = { {1, 21}, {2, 26}, {3, 16}, {4, 19}}; for (io_gpio_t offset : offsets) { auto line = chip.get_line(offset.gpio_line); // 构造请求时添加上拉偏置标志 gpiod::line_request req; req.consumer = "io"; req.request_type = gpiod::line_request::EVENT_BOTH_EDGES; req.flags = GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_UP; // 添加上拉标志 line.request(req); lines.append(line); } while (true) { gpiod::line_bulk changed_lines = lines.event_wait(std::chrono::seconds(10)); for (gpiod::line line : changed_lines) { auto event = line.event_read(); int offset = line.offset(); process_digital_in(offset, event); // Process event } } } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << std::endl; }
方式2:使用set_flags()方法设置
如果需要在请求线路后调整偏置,可以使用set_flags()方法,传入对应的偏置标志:
// 在获取线路后、请求前调用 line.set_flags(GPIOD_LINE_FLAG_BIAS_PULL_UP); line.request({"io", gpiod::line_request::EVENT_BOTH_EDGES, 100000});
需要注意的是:
- 对应的下拉偏置标志是
GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_DOWN(请求时)或GPIOD_LINE_FLAG_BIAS_PULL_DOWN(set_flags时) - 这些宏定义在libgpiod的头文件中,确保编译时正确包含
<gpiod.hpp>
内容的提问来源于stack exchange,提问作者Mendes
相关产品推荐
相关产品推荐

