Detecting Key Presses using GET and GET$ - Tutorial
004
GET
The following small program (programlet?) will show you how the
computer program can be caused to halt when it meets a GET instruction. Nothing
further will happen until the user presses a key. The program then detects
which key has been pressed and can then act accordingly.
Don't forget that you can use Shift, Control, Alt (and combinations) together
with your pressed key. Experiment! (Learn by doing).......
MODE8
PRINT "Press any key/combination of keys
" '
PRINT"to see the computer's code (ASCII)
number and printable character if any."'
REPEAT
IF VPOS>30 THEN RUN
G=GET
PRINT G;SPC(5)CHR$G
UNTIL FALSE
Notes:
- The REPEAT.....UNTIL FALSE loop repeats endlessly (until interrupted
by the RUN instruction which restarts the program)
- G=GET "reads" the ASCII code into a "variable", G, when the
key is pressed
- We print G so you can see the key's ASCII code
- PRINT CHR$(G) shows you the character that you (expect to) see
when you press this combination of keys e.g. "a" or "A"
- The line containing VPOS prevents the display scrolling off the
screen and starts the program again.
GET$ (pronounced " GET String")
The program halts at GET$ just as for GET. We can read off the
character associated with the key directly:
MODE8
PRINT "Press any key/combination of keys
" '
REPEAT
IF VPOS>30 THEN RUN
G$=GET$
PRINTTAB(5) G$
UNTIL FALSE
Halting a program.....
You don't necessarily have to do anything with G$. It can just be a useful
way of stopping the computer racing on before you can read the screen.
Try this - but make sure you don't keep a key down for long or it may never
stop.....!
MODE8
n=0
REPEAT
n=n+1
PRINT' "Go on.....press a
key!"'
G=GET
FOR i=1 TO n
PRINT i," Thank
you! "
NEXT i
UNTIL FALSE
Can you see how the "nested loops" work? (Here we have a FOR....NEXT
loop inside a REPEAT....UNTIL FALSE loop).
Exercise: Add a COLOUR statement so that every "Thank
you!" comes out in a different colour.
Next Tutorial
Richard Weston's Homepage