Skip to content

Instantly share code, notes, and snippets.

@Diviector
Created May 26, 2023 09:47
Show Gist options
  • Save Diviector/13d9b1eac590beb51c2e609ddfcd0429 to your computer and use it in GitHub Desktop.
Save Diviector/13d9b1eac590beb51c2e609ddfcd0429 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#define EVDEV "/dev/input/event0"
#define BUTTON_CODE 42
#define PRESSED 0
#define RELEASED 1
int main(int argc, char **argv) {
unsigned char key_states[KEY_MAX/8 + 1];
struct input_event evt;
int fd;
memset(key_states, 0, sizeof(key_states));
fd = open(EVDEV, O_RDONLY);
int err = errno;
if (fd < 0) {
printf("failed open " EVDEV ": %s\n", strerror(err));
return -1;
}
int rv = ioctl(fd, EVIOCGKEY(sizeof(key_states)), key_states);
err = errno;
close(fd);
if (rv < 0) {
printf("Failed ioctl: %s\n", strerror(err));
return -1;
}
int byte = BUTTON_CODE / 8;
int bit = BUTTON_CODE % 8;
int state = !!(key_states[byte] & (1 << bit));
if (state == PRESSED) {
printf("key is pressed\n");
} else {
printf("key is released\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment