In this tutorial I will explain how to use analog joysticks(Normal ones)...|
Well the analog joysticks are a bit inaccurate, you get the position of the joystick
in a weird way, related to other input devices :)
But don't worry it's still easy: the joystick position is measured using an analog potentiometer,
which can be read by calculating the timeout value of a signal on a port.
And this is the reason that they aren a bit in accurate 'cause sometimes you'll get 0 and in othertimes
you'll get 5 or 3 and etc.
OK, hope you got it 'cause this is the basis for analog joysticks...
BTW-There are two well known ways to communicate with the joystick device:
BIOS(which doesn't work on all mother boards) and by the port of the joystick 0x201(hex).
So I'll show both.
Initializing the joystick
mov dx, 1 // Function number 1 to get x/y position.
mov ah, 0x84 // Joystick....
int 0x15 // Bios interrupt...
if (_AL == 0) return(0);//AL is the result if the joystick responds or not.
int timeout = 0;
unsigned char temp;
disable(); //We tell the interrupts not to work, 'cause it might mess up the testing
outportb(0x201, 1); //Just sending any byte, and the port will respond!
while(timeout < 0xffff) //Timeout testing...Cause if the joystick isn't there the loop won't stop.
temp = inportb(0x201);
if ((temp & 0xf) != 0xf) // check if one of the first 4 bits is 0
enable();//Don't forget let the interrupts work again
Now for reading the X and Y position...
Again there are more than one way to do it...
void get_joystick_xy(unsigned short *x, unsigned short *y)
mov dx, 1
mov ah, 0x84
*x = _AX; //AX contains the X value.
*y = _BX; //BX contains the Y value.
int joystick_pos(int *x, int *y)
unsigned char tmp;
(*x) = (*y) = 0;
tmp = inportb(0x201);
if (tmp & 0x01) (*x)++; //0x01 is X axis.
if (tmp & 0x02) (*y)++; //0x02 is Y axis.
} while ((tmp & 0x03) && ((*y) < 0xffff) && ((*x) < 0xffff));
if ((*x >= 0xffff) || (*y >= 0xffff)) return(0); //Timeout testing
Now let's see if one of the buttons is pressed:
#define BUTTON_1_A 0x10
#define BUTTON_1_B 0x20
#define BUTTON_2_A 0x40
#define BUTTON_2_B 0x80
unsigned char joystickbutton(unsigned char button)
return(~inportb(JOYSTICKPORT) &button); //Checking if our button bit is set to '1'
Note: Be warned! Most joystick controllers port are at 0x201, but some use different ports.
Turbo C - joystick.cpp
|User Contributed Comments(1)|
Comments that will hurt anyone in any way will be deleted.
Don't ask for features, advertise or curse.
If you want to leave a message to the author use the contacts,
if you have any question in relation to your comments please use the forum.
Comments which violate any of these requests will be deleted without further
Use the comment system decently.
Post your comment: