From 3564716794ca62ecc5f8368f8e78f6eb0374ad5d Mon Sep 17 00:00:00 2001 From: Fredrik Tolf Date: Fri, 14 Sep 2018 19:50:23 +0200 Subject: [PATCH] Added rpi gpio program. --- gpio.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 gpio.c 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); +} -- 2.11.0