Debian Codegraph @

examples/get_line_value.c

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 reading a single line. */
5
6 #include <errno.h>
7 #include <gpiod.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 /* Request a line as input. */
13 static struct gpiod_line_request *request_input_line(const char *chip_path,
14 unsigned int offset,
15 const char *consumer)
16 {
17 struct gpiod_request_config *req_cfg = NULL;
18 struct gpiod_line_request *request = NULL;
19 struct gpiod_line_settings *settings;
20 struct gpiod_line_config *line_cfg;
21 struct gpiod_chip *chip;
22 int ret;
23
24 chip = gpiod_chip_open(chip_path);
25 if (!chip)
26 return NULL;
27
28 settings = gpiod_line_settings_new();
29 if (!settings)
30 goto close_chip;
31
32 gpiod_line_settings_set_direction(settings, GPIOD_LINE_DIRECTION_INPUT);
33
34 line_cfg = gpiod_line_config_new();
35 if (!line_cfg)
36 goto free_settings;
37
38 ret = gpiod_line_config_add_line_settings(line_cfg, &offset, 1,
39 settings);
40 if (ret)
41 goto free_line_config;
42
43 if (consumer) {
44 req_cfg = gpiod_request_config_new();
45 if (!req_cfg)
46 goto free_line_config;
47
48 gpiod_request_config_set_consumer(req_cfg, consumer);
49 }
50
51 request = gpiod_chip_request_lines(chip, req_cfg, line_cfg);
52
53 gpiod_request_config_free(req_cfg);
54
55 free_line_config:
56 gpiod_line_config_free(line_cfg);
57
58 free_settings:
59 gpiod_line_settings_free(settings);
60
61 close_chip:
62 gpiod_chip_close(chip);
63
64 return request;
65 }
66
67 static int print_value(unsigned int offset, enum gpiod_line_value value)
68 {
69 if (value == GPIOD_LINE_VALUE_ACTIVE)
70 printf("%d=Active\n", offset);
71 else if (value == GPIOD_LINE_VALUE_INACTIVE) {
72 printf("%d=Inactive\n", offset);
73 } else {
74 fprintf(stderr, "error reading value: %s\n",
75 strerror(errno));
76 return EXIT_FAILURE;
77 }
78
79 return EXIT_SUCCESS;
80 }
81
82 int main(void)
83 {
84 /* Example configuration - customize to suit your situation. */
85 static const char *const chip_path = "/dev/gpiochip0";
86 static const unsigned int line_offset = 5;
87
88 struct gpiod_line_request *request;
89 enum gpiod_line_value value;
90 int ret;
91
92 request = request_input_line(chip_path, line_offset, "get-line-value");
93 if (!request) {
94 fprintf(stderr, "failed to request line: %s\n",
95 strerror(errno));
96 return EXIT_FAILURE;
97 }
98
99 value = gpiod_line_request_get_value(request, line_offset);
100 ret = print_value(line_offset, value);
101
102 /* not strictly required here, but if the app wasn't exiting... */
103 gpiod_line_request_release(request);
104
105 return ret;
106 }