Programming joysticks with linux
Got the idea today to add joystick support to wordwarvi, and after work, went out and bought a Logitech Dual Action game pad with rumble effect. Was quite easy to program for, I got home about 6:00, and by 6:30, had a little program able to read from the joystick, made a trip to the grocery store to buy some food, came back, cooked it, ate it, then continued programming, and by 9:00, pretty much had my game running with joystick support. Didn’t try to do any rumble effects, and it’s a bit twitchy. Not sure how much of that is just the game not being suited to joystick control, and how much is just my programming needing to be tweaked to modulate the input to smooth things out, and how much is my ineptitude at wielding a joystick.
Here is my joystick code:
It’s quite easy to program, once you plug in the joystick to a USB port, device nodes appear (courtesy of udev) in /dev/input/js0, etc. You just open that up, and do a read (blocking or nonblocking, whichever you like) which gives you an event structure which contains the event type which tells you whether the event is a button press or a stick movement, a number (which indicates what button or axis was pressed or moved, e.g. 0 means stick 1, x axis, (or button 0, depending on the event type). There’s also a value, which contains, er, the value — for button presses, 1 indicates the button was pressed, 0 indicates it was released. Axis movements are signed shorts, ranging from -32768 to 32767. This is easy to figure out what’s what, you just use the “jstest” program.
jstest --normal /dev/input/js0
Then you fiddle with the joystick and watch what jstest prints out. It becomes pretty obvious what the data looks like.
You should also read the kernel documentation. Search google for “joystick-api.txt“, or download the kernel source from kernel.org, and look in Documentation/input/joystick-api.txt.
Very surprising how easy it is to read the joystick from a program.