Reading the Commodore 64 joystick

The Commodore 64 is a remarkably flexible machine, and comes with a pre-loaded BASIC interpreter. Whilst only an implementation of BASIC, it provides the budding 8-bit programmer with ability to both read any write to any of the Commodore's 6510 memory addresses, the PEEK and POKE commands, respectively.

By using the PEEK command, and a tiny little bit of bitwise mathematics, you can control pretty much any peripheral or gadget connected to your humble Commodore, and most importantly, the joystick. Controlling both the joystick and sprites is perhaps one of the most entertaining things you can do from within a BASIC program, because once you've got a sprite under joystick control, you've practically written a game.

The joystick handling code

The following code will check the input of the joystick plugged into port one. It does this by PEEKing at the memory address numbered 56321, performing a bitwise and on the value returned, and checking what the result is. Line 20 is technically not needed, all it does is reposition the cursor to the top-left to keep the output neat and tidy.

By comparing the result of the PEEK command, which is stored as J, for joystick (geddit?) with some predefined values in lines 30 to 70, you can see which way the joystick has been pushed, or if the fire button has been pushed. Magic!