84 lines
1.8 KiB
C
84 lines
1.8 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) {
|
|
char buf[64];
|
|
struct stat statBuf;
|
|
int pinExported = -1;
|
|
|
|
sprintf(buf, "/sys/class/gpio/gpio%s/direction", pin);
|
|
|
|
if (stat(buf, &statBuf) != 0)
|
|
writeToFile("/sys/class/gpio/export", 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;
|
|
}
|