9 static const int bmap[] = {
11 -1, -1, 2, -1, 3, -1, 4, 14, -1, 15, 17, 18, 27, -1, 22, 23, -1, 24, 10, -1,
12 9, 25, 11, 8, -1, 7, -1, -1, 5, -1, 6, 12, 13, -1, 19, 16, 21, 20, -1, 21,
14 static const int imap[] = {
15 -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
16 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, 27,
18 static const int *umap = bmap;
19 static int mapn = sizeof(bmap) / sizeof(*bmap);
20 static int preserve = 0;
22 static int mappin(int num)
24 if((num < 0) || (num >= mapn))
29 static void export(int p)
35 if((rp = mappin(p)) < 0)
36 errx(1, "%i: no such port\n", p);
37 sprintf(path, "/sys/class/gpio/gpio%i", rp);
38 if(!access(path, R_OK | X_OK))
41 errx(2, "gpio%i: not exported", rp);
42 sprintf(path, "/sys/class/gpio/export");
43 if((fp = fopen(path, "w")) == NULL)
45 fprintf(fp, "%i\n", rp); fflush(fp);
47 errx(1, "gpio%i: could not export", rp);
49 sprintf(path, "/sys/class/gpio/gpio%i", rp);
50 if(access(path, R_OK | X_OK))
51 errx(1, "gpio%i: still not available after export", rp);
54 static void setport(int p, int v)
56 char path[256], line[256];
60 if((rp = mappin(p)) < 0)
61 errx(1, "%i: no such port\n", p);
62 sprintf(path, "/sys/class/gpio/gpio%i/direction", rp);
63 if((fp = fopen(path, "r")) == NULL)
65 rv = !!fgets(line, sizeof(line), fp);
67 if(!rv || strcmp(line, "out\n")) {
69 errx(2, "gpio%i: not set to output", rp);
70 if((fp = fopen(path, "w")) == NULL)
72 fprintf(fp, "out\n"); fflush(fp);
74 errx(1, "gpio%i: could not set to output", rp);
77 sprintf(path, "/sys/class/gpio/gpio%i/value", rp);
78 if((fp = fopen(path, "w")) == NULL)
80 fprintf(fp, "%i\n", v); fflush(fp);
82 errx(1, "gpio%i: could not set value", rp);
86 static void usage(FILE *out)
88 fprintf(out, "usage: gpio [-hip] PORT=VAL...\n");
91 int main(int argc, char **argv)
96 while((c = getopt(argc, argv, "hip")) >= 0) {
103 mapn = sizeof(imap) / sizeof(*imap);
117 for(i = optind; i < argc; i++) {
118 if((p = strchr(argv[i], '=')) == NULL) {
119 fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
122 port = strtol(argv[i], &e, 10);
124 fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
127 val = strtol(p + 1, &e, 10);
129 fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
140 * compile-command: "gcc -Wall -g -O2 -march=native -o gpio gpio.c"