From: Fredrik Tolf Date: Fri, 14 Sep 2018 17:50:23 +0000 (+0200) Subject: Added rpi gpio program. X-Git-Url: http://www.dolda2000.com/gitweb/?a=commitdiff_plain;h=3564716794ca62ecc5f8368f8e78f6eb0374ad5d;hp=f3768fd2a1161cf3cc7e67f002cb0055f9defd05;p=utils.git Added rpi gpio program. --- diff --git a/gpio.c b/gpio.c new file mode 100644 index 0000000..babc061 --- /dev/null +++ b/gpio.c @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include +#include +#include + +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); +}