Template:LIBGPIOD V1 C EXAMPLE

From Variscite Wiki
Revision as of 13:52, 5 March 2025 by Bruno (talk | contribs) (Created page with "== libgpiod C Application == [{{#var:LIBGPIOD_URL}} libgpiod] provides bindings for C/C++ applications. C++ examples are available in the libgpiod [{{#var:LIBGPIOD_URL}}/tree/bindings/cxx/examples /tree/bindings/cxx/examples ] directory. Below is a simple C application demonstrating how to use the bindings with GPIO4_IO21: '''Makefile:''' all: main.cpp $(CC) $(CCFLAGS) -Og -lgpiod main.c -g -o hello.bin clean: rm -f hello.bin '''main.c''' <pre> #include <gpiod....")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

libgpiod C Application

[ libgpiod] provides bindings for C/C++ applications. C++ examples are available in the libgpiod [/tree/bindings/cxx/examples /tree/bindings/cxx/examples ] directory.

Below is a simple C application demonstrating how to use the bindings with GPIO4_IO21:

Makefile:

all: main.cpp
	$(CC) $(CCFLAGS) -Og -lgpiod main.c -g -o hello.bin
clean:
	rm -f hello.bin

main.c

#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define    CONSUMER    "Variscite Demo"

int main(int argc, char **argv)
{
    unsigned int i, ret, val;
    struct gpiod_chip *chip;
    struct gpiod_line *line;
    const char * chipname = "gpiochip3";
    const unsigned int line_num = 21;

    chip = gpiod_chip_open_by_name(chipname);
    if (!chip) {
        perror("Open chip failed\n");
        goto end;
    }

    line = gpiod_chip_get_line(chip, line_num);
    if (!line) {
        perror("Get line failed\n");
        goto close_chip;
    }

    ret = gpiod_line_request_output(line, CONSUMER, 0);
    if (ret < 0) {
        perror("Request line as output failed\n");
        goto release_line;
    }

    /* Blink 5 times */
    val = 0;
    for (i = 0; i < 5; i++) {
        ret = gpiod_line_set_value(line, val);
        if (ret < 0) {
            perror("Set line output failed\n");
            goto release_line;
        }
        printf("Output %u on line #%u\n", val, line_num);
        sleep(1);
        val = !val;
    }

release_line:
    gpiod_line_release(line);
close_chip:
    gpiod_chip_close(chip);
end:
    return 0;
}