Added rpi gpio program.
authorFredrik Tolf <fredrik@dolda2000.com>
Fri, 14 Sep 2018 17:50:23 +0000 (19:50 +0200)
committerFredrik Tolf <fredrik@dolda2000.com>
Fri, 14 Sep 2018 17:50:23 +0000 (19:50 +0200)
gpio.c [new file with mode: 0644]

diff --git a/gpio.c b/gpio.c
new file mode 100644 (file)
index 0000000..babc061
--- /dev/null
+++ b/gpio.c
@@ -0,0 +1,60 @@
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <err.h>
+
+static void setport(int p, int v)
+{
+    char path[256], line[256];
+    FILE *fp;
+    int rv;
+    
+    sprintf(path, "/sys/class/gpio/gpio%i/direction", p);
+    if((fp = fopen(path, "r")) == NULL)
+       err(1, "%s", path);
+    rv = !!fgets(line, sizeof(line), fp);
+    fclose(fp);
+    if(!rv || strcmp(line, "out\n")) {
+       if((fp = fopen(path, "w")) == NULL)
+           err(1, "%s", path);
+       fprintf(fp, "out\n"); fflush(fp);
+       if(ferror(fp))
+           errx(1, "gpio%i: could not set to output", p);
+       fclose(fp);
+    }
+    sprintf(path, "/sys/class/gpio/gpio%i/value", p);
+    if((fp = fopen(path, "w")) == NULL)
+       err(1, "%s", path);
+    fprintf(fp, "%i\n", v); fflush(fp);
+    if(ferror(fp))
+       errx(1, "gpio%i: could not set value", p);
+    fclose(fp);
+}
+
+int main(int argc, char **argv)
+{
+    int i, port, val;
+    char *p, *e;
+    
+    for(i = 1; i < argc; i++) {
+       if((p = strchr(argv[i], '=')) == NULL) {
+           fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
+           exit(1);
+       }
+       port = strtol(argv[i], &e, 10);
+       if(e != p) {
+           fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
+           exit(1);
+       }
+       val = strtol(p + 1, &e, 10);
+       if(*e) {
+           fprintf(stderr, "gpio: %s: not of the form PORT=VAL\n", argv[i]);
+           exit(1);
+       }
+       setport(port, val);
+    }
+    return(0);
+}