| 1 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 2 | // SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]> |
| 3 | |
| 4 | /* Minimal example of watching for rising edges on a single line. */ |
| 5 | |
| 6 | #include <cstdlib> |
| 7 | #include <filesystem> |
| 8 | #include <gpiod.hpp> |
| 9 | #include <iomanip> |
| 10 | #include <iostream> |
| 11 | |
| 12 | namespace { |
| 13 | |
| 14 | /* Example configuration - customize to suit your situation. */ |
| 15 | const ::std::filesystem::path chip_path("/dev/gpiochip0"); |
| 16 | const ::gpiod::line::offset line_offset = 5; |
| 17 | |
| 18 | const char *edge_event_type_str(const ::gpiod::edge_event &event) |
| 19 | { |
| 20 | switch (event.type()) { |
| 21 | case ::gpiod::edge_event::event_type::RISING_EDGE: |
| 22 | return "Rising"; |
| 23 | case ::gpiod::edge_event::event_type::FALLING_EDGE: |
| 24 | return "Falling"; |
| 25 | default: |
| 26 | return "Unknown"; |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | } /* namespace */ |
| 31 | |
| 32 | int main() |
| 33 | { |
| 34 | auto request = |
| 35 | ::gpiod::chip(chip_path) |
| 36 | .prepare_request() |
| 37 | .set_consumer("watch-line-value") |
| 38 | .add_line_settings( |
| 39 | line_offset, |
| 40 | ::gpiod::line_settings() |
| 41 | .set_direction( |
| 42 | ::gpiod::line::direction::INPUT) |
| 43 | .set_edge_detection( |
| 44 | ::gpiod::line::edge::RISING) |
| 45 | ) |
| 46 | .do_request(); |
| 47 | |
| 48 | /* |
| 49 | * A larger buffer is an optimisation for reading bursts of events from |
| 50 | * the kernel, but that is not necessary in this case, so 1 is fine. |
| 51 | */ |
| 52 | ::gpiod::edge_event_buffer buffer(1); |
| 53 | |
| 54 | for (;;) { |
| 55 | /* Blocks until at least one event is available. */ |
| 56 | request.read_edge_events(buffer); |
| 57 | |
| 58 | for (const auto &event : buffer) |
| 59 | ::std::cout << "line: " << event.line_offset() |
| 60 | << " type: " << ::std::setw(7) << ::std::left << edge_event_type_str(event) |
| 61 | << " event #" << event.line_seqno() |
| 62 | << ::std::endl; |
| 63 | } |
| 64 | } |