// Gerardo Marx 24/09/2026 // gpio command tool // eg. ./gpio 17 out 1 // ./gpio 17 in // ./gpio 17 blink 500(ms) #include #include #include #include // prototype functions int gpio_export(const char *gpio); int gpio_direction(const char *gpio, const char *direction); // this function int gpio_write(const char *gpio, const char *value); // write function int gpio_read(const char *gpio); //read function int gpio_unexport(const char *gpio); int main(int argc, char *argv[]){ int fd; const char *pin; const char *dir; const char *val = NULL; // checking that at least gpio and direction is passed if(argc<3){ printf("Usage:\n"); printf(" %s in\n", argv[0]); printf(" %s out \n", argv[0]); return 1; } pin = argv[1]; // get gpio number from argument dir = argv[2]; // get gpio direction from arguments //const char *val = argv[3]; // checking the gpio direction if(strcmp(dir, "out") == 0) { if(argc<4){ printf("Error: GPIO out option requires a value.\n"); printf("Usage: %s out <0|1>\n", argv[0]); return 1; } val = argv[3]; } gpio_export(pin); gpio_direction(pin, dir); gpio_write(pin, val); gpio_unexport(pin); } // comple functions // // gpio_export int gpio_export(const char *gpio){ int fd; fd = open("/sys/class/gpio/chip0/export", O_WRONLY); if(fd<0){ perror("Error opening the GPIO path during export"); return -1; } write(fd,gpio,strlen(gpio)); close(fd); return 0; } // gpio direction int gpio_direction(const char *gpio, const char *direction){ // pin direction - convert into functions int fd; char path[64]; snprintf(path, sizeof(path), "/sys/class/gpio/chip0/gpio%s/direction", gpio); fd = open(path, O_WRONLY); //gpio number if(fd<0) { perror("Error opening the GPIO path"); return -1; } write(fd,direction,strlen(direction)); close(fd); return 0; } int gpio_write(const char *gpio, const char *value){ int fd; char path[64]; snprintf(path, sizeof(path), "/sys/class/gpio/chip0/gpio%s/value", gpio); fd = open(path, O_WRONLY); if(fd<0){ perror("Error opening the GPIO path during write"); return -1; } if(write(fd,value, strlen(value)) < 0) { perror("write"); close(fd); return -1; } //write(fd, value, strlen(value)); close(fd); return 0; } // gpio read int gpio_read(const char *gpio); //read function // unexport int gpio_unexport(const char *gpio){ int fd; fd = open("/sys/class/gpio/chip0/unexport", O_WRONLY); if(fd<0) { perror("Error opening the GPIO path during unexport"); return -1; } if(write(fd,gpio, strlen(gpio)) < 0) { perror("unexport"); close(fd); return -1; } close(fd); return 0; }