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.
20 PRINT CHR$(147)
30 IF (J AND1) THEN PRINT "UP ";
40 IF (J AND2) THEN PRINT "DOWN ";
50 IF (J AND4) THEN PRINT "LEFT ";
60 IF (J AND8) THEN PRINT "RIGHT ";
70 IF (J AND16)THEN PRINT "FIRE! ";
80 GOTO 10
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!
If having control of the joystick has whetted your appetite for Commodore hacking, take a look at these nodes: