guowenxue
2021-08-09 45535c46b444c4ae33ee1e974bb06abf7254a132
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*********************************************************************************
 *      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;
}