You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
c-gpio-intro/main.c

111 lines
2.0 KiB
C

// Gerardo Marx 24/09/2026
// gpio command tool
// eg. ./gpio 17 out 1
// ./gpio 17 in
// ./gpio 17 blink 500(ms)
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
// prototype functions
int gpio_export(const char *gpio);
int gpio_direction(const char *gpio, const char *direction); // this function
int gpio_write(int gpio, int value);
int main(int argc, char *argv[]){
int fd;
const char *pin = argv[1]; // get gpio number from argument
const char *dir = argv[2]; // get gpio direction from arguments
//
gpio_export(pin);
gpio_direction(pin, dir);
// pin value to 1
fd = open("/sys/class/gpio/chip0/gpio17/value", O_WRONLY);
if(fd<0)
{
perror("Error opening the GPIO path");
return -1;
}
write(fd,"1",1);
close(fd);
sleep(1);
// pin valu to 0
fd = open("/sys/class/gpio/chip0/gpio17/value", O_WRONLY);
if(fd<0)
{
perror("Error opening the GPIO path");
return -1;
}
write(fd,"0",1);
close(fd);
sleep(1);
// unexport
fd = open("/sys/class/gpio/chip0/unexport", O_WRONLY);
if(fd<0)
{
perror("Error opening the GPIO path");
return -1;
}
write(fd,"17",2);
close(fd);
printf("Hello from Raspberry Pi!\n");
printf("Number of arguments: %d\n", argc);
printf("Program is reciving: %s\n", argv[0]);
if(argc > 1 )
printf("Argument: %s\n", argv[1]);
return 0;
}
// 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");
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;
}