Debian Codegraph @

examples/toggle_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 toggling 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 #include <unistd.h>
12
13 static struct gpiod_line_request *
14 request_output_line(const char *chip_path, unsigned int offset,
15 enum gpiod_line_value value, 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,
33 GPIOD_LINE_DIRECTION_OUTPUT);
34 gpiod_line_settings_set_output_value(settings, value);
35
36 line_cfg = gpiod_line_config_new();
37 if (!line_cfg)
38 goto free_settings;
39
40 ret = gpiod_line_config_add_line_settings(line_cfg, &offset, 1,
41 settings);
42 if (ret)
43 goto free_line_config;
44
45 if (consumer) {
46 req_cfg = gpiod_request_config_new();
47 if (!req_cfg)
48 goto free_line_config;
49
50 gpiod_request_config_set_consumer(req_cfg, consumer);
51 }
52
53 request = gpiod_chip_request_lines(chip, req_cfg, line_cfg);
54
55 gpiod_request_config_free(req_cfg);
56
57 free_line_config:
58 gpiod_line_config_free(line_cfg);
59
60 free_settings:
61 gpiod_line_settings_free(settings);
62
63 close_chip:
64 gpiod_chip_close(chip);
65
66 return request;
67 }
68
69 static enum gpiod_line_value toggle_line_value(enum gpiod_line_value value)
70 {
71 return (value == GPIOD_LINE_VALUE_ACTIVE) ? GPIOD_LINE_VALUE_INACTIVE :
72 GPIOD_LINE_VALUE_ACTIVE;
73 }
74
75 static const char * value_str(enum gpiod_line_value value)
76 {
77 if (value == GPIOD_LINE_VALUE_ACTIVE)
78 return "Active";
79 else if (value == GPIOD_LINE_VALUE_INACTIVE) {
80 return "Inactive";
81 } else {
82 return "Unknown";
83 }
84 }
85
86 int main(void)
87 {
88 /* Example configuration - customize to suit your situation. */
89 static const char *const chip_path = "/dev/gpiochip0";
90 static const unsigned int line_offset = 5;
91
92 enum gpiod_line_value value = GPIOD_LINE_VALUE_ACTIVE;
93 struct gpiod_line_request *request;
94
95 request = request_output_line(chip_path, line_offset, value,
96 "toggle-line-value");
97 if (!request) {
98 fprintf(stderr, "failed to request line: %s\n",
99 strerror(errno));
100 return EXIT_FAILURE;
101 }
102
103 for (;;) {
104 printf("%d=%s\n", line_offset, value_str(value));
105 sleep(1);
106 value = toggle_line_value(value);
107 gpiod_line_request_set_value(request, line_offset, value);
108 }
109
110 gpiod_line_request_release(request);
111
112 return EXIT_SUCCESS;
113 }