From 7baed996272cd3c889a5ab714c2b3391703f75f1 Mon Sep 17 00:00:00 2001 From: guowenxue <guowenxue@gmail.com> Date: Sat, 23 Jan 2021 19:44:10 +0800 Subject: [PATCH] Add gpiod.c for libgpiod output sample code --- modules/c/led.c | 2 modules/c/gpiod.c | 91 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletions(-) diff --git a/modules/c/gpiod.c b/modules/c/gpiod.c new file mode 100644 index 0000000..3ad04bd --- /dev/null +++ b/modules/c/gpiod.c @@ -0,0 +1,91 @@ +/********************************************************************************* + * Copyright: (C) 2021 LingYun IoT System Studio + * All rights reserved. + * + * Filename: gpiod.c + * Description: This file is used to control a pin GPIO output by libgpiod + * + * pi@raspberrypi:~ $ gpio readall show BCM and wPi pinmap + * + * + * Version: 1.0.0(2021/01/23) + * Author: Guo Wenxue <guowenxue@gmail.com> + * ChangeLog: 1, Release initial version on "2021/01/23 12:13:26" + * + ********************************************************************************/ + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <dirent.h> +#include <string.h> +#include <time.h> +#include <errno.h> + +#include <gpiod.h> + +void gpiod_ctxless_cb(void *data) +{ + sleep(1); +} + +int main(int argc, char *argv[]) +{ + struct gpiod_chip *chip; + struct gpiod_line *line; + int bcm_pin; + int level; + + if( argc != 3 ) + { + printf(" Usage: sudo %s [BCM Pin number] [1/0]\n", argv[0]); + printf("example, turn BCM Pin #6 lowlevel : sudo %s 6 0\n", argv[0]); + printf("example, turn BCM Pin #6 highlevel: sudo %s 6 1\n", argv[0]); + } + + bcm_pin = atoi(argv[1]); + level = atoi(argv[2]); +#if 0 + if( level ) + gpiod_ctxless_set_value("gpiochip0", bcm_pin, 1, false, "led", gpiod_ctxless_cb, NULL); + else + gpiod_ctxless_set_value("gpiochip0", bcm_pin, 0, false, "led", gpiod_ctxless_cb, NULL); +#else + chip = gpiod_chip_open_by_name("gpiochip0"); + if( !chip ) + { + printf("gpiod open chip failure, maybe you need running as root\n"); + exit(1); + } + + line = gpiod_chip_get_line(chip, bcm_pin); + if( !line ) + { + printf("gpiod get line for BCM pin [#%d] failure\n", bcm_pin); + exit(1); + } + + gpiod_line_request_output(line, "led", 1); + + printf("set BCM pin #%d as %s level\n", bcm_pin, level?"high":"low"); + + if( level ) + { + gpiod_line_set_value(line, 1); + } + else + { + gpiod_line_set_value(line, 0); + } + + sleep(1); /* must add sleep here, or it will not take effect */ + + gpiod_line_release(line); + gpiod_chip_close(chip); +#endif + + return 0; +} + + diff --git a/modules/c/led.c b/modules/c/led.c index 2bf3df8..5ef2c0c 100644 --- a/modules/c/led.c +++ b/modules/c/led.c @@ -91,7 +91,7 @@ #include <gpiod.h> -#if 1 /* Use libgpiod lowlevel API */ +#if 0 /* Use libgpiod lowlevel API */ struct gpiod_chip* chip; -- Gitblit v1.9.1