#define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #define GPIO "512" #define MAX_BUF 64 void set_realtime_priority(int priority) { struct sched_param sched; sched.sched_priority = priority; if (sched_setscheduler(0, SCHED_FIFO, &sched) != 0) { perror("sched_setscheduler"); exit(EXIT_FAILURE); } } void set_cpu_affinity(int core_id) { cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core_id, &cpuset); if (sched_setaffinity(0, sizeof(cpuset), &cpuset) != 0) { perror("sched_setaffinity"); exit(EXIT_FAILURE); } } void export_gpio() { char path[MAX_BUF]; int fd = open("/sys/class/gpio/export", O_WRONLY); if (fd < 0 && errno != EBUSY) { perror("export"); exit(EXIT_FAILURE); } if (fd >= 0) { write(fd, GPIO, strlen(GPIO)); close(fd); } snprintf(path, sizeof(path), "/sys/class/gpio/gpio%s/direction", GPIO); fd = open(path, O_WRONLY); write(fd, "in", 2); close(fd); snprintf(path, sizeof(path), "/sys/class/gpio/gpio%s/edge", GPIO); fd = open(path, O_WRONLY); write(fd, "rising", 6); close(fd); } int main(int argc, char *argv[]) { char path[MAX_BUF]; struct pollfd pfd; struct timespec ts; int core = 1; // Run on CPU core 1 int priority = 90; // Real-time priority set_cpu_affinity(core); set_realtime_priority(priority); export_gpio(); snprintf(path, sizeof(path), "/sys/class/gpio/gpio%s/value", GPIO); pfd.fd = open(path, O_RDONLY); if (pfd.fd < 0) { perror("gpio value open"); exit(EXIT_FAILURE); } pfd.events = POLLPRI | POLLERR; lseek(pfd.fd, 0, SEEK_SET); char buf[8]; read(pfd.fd, buf, sizeof(buf)); // Clear initial state while (1) { poll(&pfd, 1, -1); lseek(pfd.fd, 0, SEEK_SET); read(pfd.fd, buf, sizeof(buf)); // Clear interrupt if (clock_gettime(CLOCK_REALTIME, &ts) == 0) { printf("%ld.%09ld\n", ts.tv_sec, ts.tv_nsec); fflush(stdout); } else { perror("clock_gettime"); } } close(pfd.fd); return 0; }