Created
December 18, 2015 06:58
-
-
Save Ishotihadus/bcd052346a07d8c6f634 to your computer and use it in GitHub Desktop.
ラズパイのGPIOにアクセスする既存のライブラリが使えなかったので自分で作った。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#define INPUT 0 | |
#define OUTPUT 1 | |
typedef struct | |
{ | |
int id; | |
} GPIO; | |
int gpio_open(int id, char* mode) | |
{ | |
FILE *fp; | |
char filename[128]; | |
fp = fopen("/sys/class/gpio/export", "w"); | |
if(fp == NULL) | |
return -1; | |
fprintf(fp, "%d", id); | |
fclose(fp); | |
sprintf(filename, "/sys/class/gpio/gpio%d/direction", id); | |
fp = fopen(filename, "w"); | |
if(fp == NULL) | |
return -1; | |
fprintf(fp, "%s", mode); | |
fclose(fp); | |
return 0; | |
} | |
GPIO gpio_open_reader(int id) | |
{ | |
GPIO gpio = { -1 }; | |
if(gpio_open(id, "in") == -1) | |
return gpio; | |
gpio.id = id; | |
return gpio; | |
} | |
int gpio_read(GPIO gpio) | |
{ | |
int fd; | |
char filename[128]; | |
char c; | |
sprintf(filename, "/sys/class/gpio/gpio%d/value", gpio.id); | |
fd = open(filename, O_RDONLY); | |
read(fd, &c, 1); | |
close(fd); | |
return c == '1' ? 1 : 0; | |
} | |
GPIO gpio_open_writer(int id) | |
{ | |
GPIO gpio = { -1 }; | |
if(gpio_open(id, "out") == -1) | |
return gpio; | |
gpio.id = id; | |
return gpio; | |
} | |
int gpio_write(GPIO gpio, int data) | |
{ | |
int fd; | |
char filename[128]; | |
char c[2] = {'0', '1'}; | |
sprintf(filename, "/sys/class/gpio/gpio%d/value", gpio.id); | |
fd = open(filename, O_WRONLY); | |
write(fd, c + (data ? 1 : 0), 1); | |
close(fd); | |
return 0; | |
} | |
int gpio_close(GPIO gpio) | |
{ | |
FILE *fp; | |
fp = fopen("/sys/class/gpio/unexport", "w"); | |
if(fp == NULL) | |
return -1; | |
fprintf(fp, "%d", gpio.id); | |
fclose(fp); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment