| 1 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 2 | // SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]> |
| 3 | |
| 4 | /* Minimal example of asynchronously watching for edges on a single line. */ |
| 5 | |
| 6 | #include <cstdlib> |
| 7 | #include <cstring> |
| 8 | #include <filesystem> |
| 9 | #include <gpiod.hpp> |
| 10 | #include <iomanip> |
| 11 | #include <iostream> |
| 12 | #include <poll.h> |
| 13 | |
| 14 | namespace { |
| 15 | |
| 16 | /* Example configuration - customize to suit your situation. */ |
| 17 | const ::std::filesystem::path chip_path("/dev/gpiochip0"); |
| 18 | const ::gpiod::line::offset line_offset = 5; |
| 19 | |
| 20 | const char* edge_event_type_str(const ::gpiod::edge_event &event) |
| 21 | { |
| 22 | switch (event.type()) { |
| 23 | case ::gpiod::edge_event::event_type::RISING_EDGE: |
| 24 | return "Rising "; |
| 25 | case ::gpiod::edge_event::event_type::FALLING_EDGE: |
| 26 | return "Falling"; |
| 27 | default: |
| 28 | return "Unknown"; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | } /* namespace */ |
| 33 | |
| 34 | int main() |
| 35 | { |
| 36 | /* |
| 37 | * Assume a button connecting the pin to ground, so pull it up and |
| 38 | * provide some debounce. |
| 39 | */ |
| 40 | auto request = |
| 41 | ::gpiod::chip(chip_path) |
| 42 | .prepare_request() |
| 43 | .set_consumer("async-watch-line-value") |
| 44 | .add_line_settings( |
| 45 | line_offset, |
| 46 | ::gpiod::line_settings() |
| 47 | .set_direction( |
| 48 | ::gpiod::line::direction::INPUT) |
| 49 | .set_edge_detection( |
| 50 | ::gpiod::line::edge::BOTH) |
| 51 | .set_bias(::gpiod::line::bias::PULL_UP) |
| 52 | .set_debounce_period( |
| 53 | std::chrono::milliseconds(10))) |
| 54 | .do_request(); |
| 55 | |
| 56 | /* |
| 57 | * A larger buffer is an optimisation for reading bursts of events from |
| 58 | * the kernel, but that is not necessary in this case, so 1 is fine. |
| 59 | */ |
| 60 | ::gpiod::edge_event_buffer buffer(1); |
| 61 | |
| 62 | struct pollfd pollfd; |
| 63 | pollfd.fd = request.fd(); |
| 64 | pollfd.events = POLLIN; |
| 65 | |
| 66 | for (;;) { |
| 67 | /* |
| 68 | * Other fds could be registered with the poll and be handled |
| 69 | * separately using the pollfd.revents after poll() |
| 70 | */ |
| 71 | auto ret = poll(&pollfd, 1, -1); |
| 72 | if (ret == -1) { |
| 73 | ::std::cerr << "error waiting for edge events: " |
| 74 | << strerror(errno) << ::std::endl; |
| 75 | |
| 76 | return EXIT_FAILURE; |
| 77 | } |
| 78 | |
| 79 | request.read_edge_events(buffer); |
| 80 | |
| 81 | for (const auto& event : buffer) |
| 82 | ::std::cout << "offset: " << event.line_offset() |
| 83 | << " type: " << ::std::setw(7) |
| 84 | << ::std::left << edge_event_type_str(event) |
| 85 | << " event #" << event.line_seqno() |
| 86 | << ::std::endl; |
| 87 | } |
| 88 | } |