Files
bell-rspro/gpiosysfs.c
2020-10-26 20:07:30 +01:00

86 lines
1.9 KiB
C

#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <stdio.h> /* printf(), snprintf() */
#include <stdlib.h> /* strtol(), exit() */
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include "gpiosysfs.h"
static void writeToFile(const char *absoluteFileName, const char *contents) {
int fd = open(absoluteFileName, O_WRONLY);
if (-1 == fd) {
fprintf(stderr, "Couldn't open %s for writing!\n", absoluteFileName);
exit(1);
}
int contentsLength = strlen(contents);
if (write(fd, contents, contentsLength) != contentsLength) {
fprintf(stderr, "Failed to write entire value %s to %s!\n", contents, absoluteFileName);
close(fd);
exit(1);
}
close(fd);
}
void gpioSetup(const char *pin) {
// TODO only export if not already exported...
if (access("/sys/class/gpio/unexport",W_OK) == 0)
writeToFile("/sys/class/gpio/unexport", pin);
writeToFile("/sys/class/gpio/export", pin);
char buf[33];
struct stat statBuf;
int pinExported = -1;
sprintf(buf, "/sys/class/gpio/gpio%s/direction", pin);
// May have to briefly wait for OS to make symlink!
while (pinExported != 0) {
msleep(1000);
pinExported = stat(buf, &statBuf);
}
writeToFile(buf, "out");
}
void gpioCleanup(const char *pin) {
writeToFile("/sys/class/gpio/unexport", pin);
}
void gpioWrite(const char *pin, const char *val) {
char buf[29];
sprintf(buf, "/sys/class/gpio/gpio%s/value", pin);
writeToFile(buf, val);
}
/* msleep(): Sleep for the requested number of milliseconds. */
int msleep(long msec)
{
struct timespec ts;
int res;
if (msec < 0)
{
errno = EINVAL;
return -1;
}
ts.tv_sec = msec / 1000;
ts.tv_nsec = (msec % 1000) * 1000000;
do {
res = nanosleep(&ts, &ts);
} while (res && errno == EINTR);
return res;
}