Debian Codegraph @

bindings/cxx/examples/watch_line_value.cpp

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 // SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
3
4 /* Minimal example of watching for 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 /*
35 * Assume a button connecting the pin to ground, so pull it up and
36 * provide some debounce.
37 */
38 auto request =
39 ::gpiod::chip(chip_path)
40 .prepare_request()
41 .set_consumer("watch-line-value")
42 .add_line_settings(
43 line_offset,
44 ::gpiod::line_settings()
45 .set_direction(
46 ::gpiod::line::direction::INPUT)
47 .set_edge_detection(
48 ::gpiod::line::edge::BOTH)
49 .set_bias(::gpiod::line::bias::PULL_UP)
50 .set_debounce_period(
51 std::chrono::milliseconds(10)))
52 .do_request();
53
54 /*
55 * A larger buffer is an optimisation for reading bursts of events from
56 * the kernel, but that is not necessary in this case, so 1 is fine.
57 */
58 ::gpiod::edge_event_buffer buffer(1);
59
60 for (;;) {
61 /* Blocks until at least one event is available. */
62 request.read_edge_events(buffer);
63
64 for (const auto &event : buffer)
65 ::std::cout << "line: " << event.line_offset()
66 << " type: " << ::std::setw(7)
67 << ::std::left << edge_event_type_str(event)
68 << " event #" << event.line_seqno()
69 << ::std::endl;
70 }
71 }