guowenxue
2021-01-23 7baed996272cd3c889a5ab714c2b3391703f75f1
Add gpiod.c for libgpiod output sample code
1 files modified
1 files added
93 ■■■■■ changed files
modules/c/gpiod.c 91 ●●●●● patch | view | raw | blame | history
modules/c/led.c 2 ●●● patch | view | raw | blame | history
modules/c/gpiod.c
New file
@@ -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;
}
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;