Debian Codegraph @

bindings/glib/examples/watch_line_value_glib.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 // SPDX-FileCopyrightText: 2023-2024 Bartosz Golaszewski <[email protected]>
3
4 /* Minimal example of asynchronously watching for edges on a single line. */
5
6 #include <glib.h>
7 #include <gpiod-glib.h>
8 #include <stdlib.h>
9
10 static void on_edge_event(GpiodglibLineRequest *request G_GNUC_UNUSED,
11 GpiodglibEdgeEvent *event,
12 gpointer data G_GNUC_UNUSED)
13 {
14 g_autoptr(GString) event_name = NULL;
15 guint64 timestamp;
16 guint offset;
17
18 event_name = g_string_new(
19 g_enum_to_string(GPIODGLIB_EDGE_EVENT_TYPE_TYPE,
20 gpiodglib_edge_event_get_event_type(event)));
21 g_string_replace(event_name, "GPIODGLIB_EDGE_EVENT_", "", 0);
22 timestamp = gpiodglib_edge_event_get_timestamp_ns(event);
23 offset = gpiodglib_edge_event_get_line_offset(event);
24
25 g_print("%s %lu %u\n", event_name->str, timestamp, offset);
26 }
27
28 int main(void)
29 {
30 /* Example configuration - customize to suit your situation. */
31 static const gchar *const chip_path = "/dev/gpiochip1";
32 static const guint line_offset = 5;
33
34 g_autoptr(GpiodglibRequestConfig) req_cfg = NULL;
35 g_autoptr(GpiodglibLineSettings) settings = NULL;
36 g_autoptr(GpiodglibLineRequest) request = NULL;
37 g_autoptr(GpiodglibLineConfig) line_cfg = NULL;
38 g_autoptr(GpiodglibChip) chip = NULL;
39 g_autoptr(GArray) offsets = NULL;
40 g_autoptr(GMainLoop) loop = NULL;
41 g_autoptr(GError) err = NULL;
42 gboolean ret;
43
44 offsets = g_array_new(FALSE, TRUE, sizeof(guint));
45 g_array_append_val(offsets, line_offset);
46
47 chip = gpiodglib_chip_new(chip_path, &err);
48 if (!chip) {
49 g_printerr("unable to open %s: %s\n", chip_path, err->message);
50 return EXIT_FAILURE;
51 }
52
53 /*
54 * Assume a button connecting the pin to ground, so pull it up and
55 * provide some debounce.
56 */
57 settings = gpiodglib_line_settings_new(
58 "direction", GPIODGLIB_LINE_DIRECTION_INPUT,
59 "edge-detection", GPIODGLIB_LINE_EDGE_BOTH,
60 "bias", GPIODGLIB_LINE_BIAS_PULL_UP,
61 "debounce-period-us", 1000,
62 NULL);
63
64 line_cfg = gpiodglib_line_config_new();
65 ret = gpiodglib_line_config_add_line_settings(line_cfg, offsets,
66 settings, &err);
67 if (!ret) {
68 g_printerr("failed to add line settings to line config: %s",
69 err->message);
70 return EXIT_FAILURE;
71 }
72
73 req_cfg = gpiodglib_request_config_new("consumer", "watch-line-value",
74 NULL);
75
76 request = gpiodglib_chip_request_lines(chip, req_cfg, line_cfg, &err);
77 if (!request) {
78 g_printerr("failed to request lines: %s", err->message);
79 return EXIT_FAILURE;
80 }
81
82 loop = g_main_loop_new(NULL, FALSE);
83
84 /* Connect to the edge-event signal on the line-request. */
85 g_signal_connect(request, "edge-event",
86 G_CALLBACK(on_edge_event), NULL);
87
88 g_main_loop_run(loop);
89
90 return EXIT_SUCCESS;
91 }