Skip to content

Instantly share code, notes, and snippets.

@rikusalminen
Created September 10, 2016 16:24
Show Gist options
  • Save rikusalminen/972e3824350193bbed0c28ff96a82a73 to your computer and use it in GitHub Desktop.
Save rikusalminen/972e3824350193bbed0c28ff96a82a73 to your computer and use it in GitHub Desktop.
Linux force feedback hello world
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <linux/input.h>
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
#define FF_EFFECTS(FX) \
FX(FF_RUMBLE) \
FX(FF_PERIODIC) \
FX(FF_CONSTANT) \
FX(FF_SPRING) \
FX(FF_FRICTION) \
FX(FF_DAMPER) \
FX(FF_INERTIA) \
FX(FF_RAMP) \
FX(FF_SQUARE) \
FX(FF_TRIANGLE) \
FX(FF_SINE) \
FX(FF_SAW_UP) \
FX(FF_SAW_DOWN) \
FX(FF_CUSTOM)
#define GETBIT(mask, bit) \
((((uint8_t*)(mask))[(bit) / 8] & (1 << ((bit) % 8))) != 0)
static void test_joystick(const char *path) {
int err = 0;
int fd = open(path, O_RDWR);
if(fd == -1) {
fprintf(stderr, "Can't open %s: %s\n", path, strerror(errno));
return;
}
const int max_name_len = 128;
char dev_name[max_name_len];
int name_len = ioctl(fd, EVIOCGNAME(max_name_len), dev_name);
if(name_len < 0) {
fprintf(stderr, "Can't get device name %s: %s\n", path, strerror(errno));
goto fail;
}
printf("device name: %s\n", dev_name);
uint8_t ff_bits[(FF_CNT + 7) / 8];
err = ioctl(fd, EVIOCGBIT(EV_FF, sizeof(ff_bits)), ff_bits);
assert(err >= 0);
#define printit(x) \
if(GETBIT(ff_bits, x)) printf("%s\n", #x);
FF_EFFECTS(printit);
struct ff_effect fx;
fx.type = FF_RUMBLE;
fx.id = -1;
fx.direction = 0x0;
fx.trigger.button = 0;
fx.trigger.interval = 0;
fx.replay.length = 500;
fx.replay.delay = 0;
fx.u.rumble.strong_magnitude = 0x2000;
fx.u.rumble.weak_magnitude = 0x2000;
err = ioctl(fd, EVIOCSFF, &fx);
assert(err >= 0);
printf("new fx id: %d\n", fx.id);
struct input_event play;
play.type = EV_FF;
play.code = fx.id;
play.value = 3;
write(fd, (const void*)&play, sizeof(play));
sleep(5);
fail:
close(fd);
}
int main(int argc, char *argv[]) {
(void)argc; (void)argv;
test_joystick("/dev/input/event16");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment