Added rpi gpio program.
[utils.git] / gpio.c
... / ...
CommitLineData
1#include <unistd.h>
2#include <stdlib.h>
3#include <stdio.h>
4#include <string.h>
5#include <fcntl.h>
6#include <errno.h>
7#include <err.h>
8
9static void setport(int p, int v)
10{
11 char path[256], line[256];
12 FILE *fp;
13 int rv;
14
15 sprintf(path, "/sys/class/gpio/gpio%i/direction", p);
16 if((fp = fopen(path, "r")) == NULL)
17 err(1, "%s", path);
18 rv = !!fgets(line, sizeof(line), fp);
19 fclose(fp);
20 if(!rv || strcmp(line, "out\n")) {
21 if((fp = fopen(path, "w")) == NULL)
22 err(1, "%s", path);
23 fprintf(fp, "out\n"); fflush(fp);
24 if(ferror(fp))
25 errx(1, "gpio%i: could not set to output", p);
26 fclose(fp);
27 }
28 sprintf(path, "/sys/class/gpio/gpio%i/value", p);
29 if((fp = fopen(path, "w")) == NULL)
30 err(1, "%s", path);
31 fprintf(fp, "%i\n", v); fflush(fp);
32 if(ferror(fp))
33 errx(1, "gpio%i: could not set value", p);
34 fclose(fp);
35}
36
37int main(int argc, char **argv)
38{
39 int i, port, val;
40 char *p, *e;
41
42 for(i = 1; i < argc; i++) {
43 if((p = strchr(argv[i], '=')) == NULL) {
44 fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
45 exit(1);
46 }
47 port = strtol(argv[i], &e, 10);
48 if(e != p) {
49 fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
50 exit(1);
51 }
52 val = strtol(p + 1, &e, 10);
53 if(*e) {
54 fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
55 exit(1);
56 }
57 setport(port, val);
58 }
59 return(0);
60}