Skip to content

Instantly share code, notes, and snippets.

@Ar-Ray-code
Last active March 14, 2022 15:49
Show Gist options
  • Save Ar-Ray-code/751815833d521ecbc2a06c35729ef77a to your computer and use it in GitHub Desktop.
Save Ar-Ray-code/751815833d521ecbc2a06c35729ef77a to your computer and use it in GitHub Desktop.
JoyStick(PS5)の左ジョイスティックをマウスカーソルと連動させる練習用プログラム
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <X11/Xlib.h>
// #include <X11/Xutil.h>
#include <linux/joystick.h>
#define JOY_DEV "/dev/input/js0"
int open_joy()
{
int fd = open(JOY_DEV, O_RDONLY);
if (fd < 0)
{
perror("error opening joystick");
exit(1);
}
return fd;
}
long int map(int value, int min, int max, int min_out, int max_out)
{
return (value - min) * (max_out - min_out) / (max - min) + min_out;
}
int main(void)
{
struct js_event e;
int raw_joy_x, raw_joy_y;
int raw_joy_x_buf, raw_joy_y_buf = 0;
int cursor_x, cursor_y;
int joy_x, joy_y;
int height, width;
Display *display = XOpenDisplay(NULL);
XEvent event = {0x00};
int scr = XDefaultScreen(display);
Window root_window = XRootWindow(display, scr);
height = DisplayHeight(display, scr);
width = DisplayWidth(display, scr);
std::cout << "width: " << width << " height: " << height << std::endl;
int fd = open_joy();
while (read(fd, &e, sizeof(e)) > 0)
{
if (e.type & JS_EVENT_AXIS)
{
if (e.number == 0)
{
raw_joy_x = e.value;
raw_joy_x_buf = raw_joy_x;
}
else if (e.number == 1)
{
raw_joy_y = e.value;
raw_joy_y_buf = raw_joy_y;
}
}
// not working ... :(
// if (e.type & JS_EVENT_BUTTON)
// {
// // cross button -> click pointer
// if (e.value == 1)
// {
// event.type = ButtonPress;
// event.xbutton.button = 1;
// XSendEvent(display, root_window, True, 0xfff, &event);
// // XFlush(display);
// usleep(100);
// std::cout << "click" << std::endl;
// // left click
// event.type = ButtonRelease;
// event.xbutton.state = 0x100;
// XSendEvent(display, root_window, True, 0xfff, &event);
// // XFlush(display);
// }
// }
std::cout << "raw_x: " << raw_joy_x << " raw_y: " << raw_joy_y << std::endl;
joy_x = map(raw_joy_x, -32767, 32767, -100, 100);
joy_y = map(raw_joy_y, -32767, 32767, -100, 100);
if (abs(joy_x) > 10)
cursor_x += (int)joy_x / 10;
if (abs(joy_y) > 10)
cursor_y += (int)joy_y / 10;
// max=display_width
if (cursor_x > width) cursor_x = width;
if (cursor_x < 0) cursor_x = 0;
if (cursor_y > height) cursor_y = height;
if (cursor_y < 0) cursor_y = 0;
std::cout << "joy_x: " << joy_x << " joy_y: " << joy_y << " cursor_x: " << cursor_x << " cursor_y: " << cursor_y << std::endl;
XWarpPointer(display, None, root_window, 0, 0, 0, 0, cursor_x, cursor_y);
XFlush(display);
// usleep(100);
}
return 0;
}
// g++ joy2cursor.cpp -o joy2cursor -lX11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment