Upcoming Events
Unite 2010
11/10 - 11/12 @ Montréal, Canada

GDC China
12/5 - 12/7 @ Shanghai, China

Asia Game Show 2010
12/24 - 12/27  

GDC 2011
2/28 - 3/4 @ San Francisco, CA

More events...
Quick Stats
64 people currently visiting GDNet.
2406 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!
Link to us Events 4 Gamers
Intel sponsors gamedev.net search:

Contents
 Getting Input
 Example

 Printable version
 Discuss this article

The Series
 Volume I
 Volume II
 Volume III

What will this article cover?

This article is going to be short and sweet. It’s going to cover input, a remarkably easy topic that should be refreshing after the last volume. In fact, I’m not even sure this article is worthy of a whole volume, but this is how I’m going to do it anyhow.

Getting Input

Unlike the PC where you have a gagillion different possible input devices, we’re blessed enough to only have one to deal with.  What’s more, this input device is simple enough to cover swiftly and efficiently.

Input from the keypad is detected in a single register located at 0x4000130.  Thus, our definition would look something like this:

#define KEYS  (*(volatile u16*)0x4000130)

OR we could use the version defined in gba.h called REG_P1.  It’s already defined, so you wouldn’t need the above snippet.  However, I like using the name KEYS instead of REG_P1 because it seems more explanatory to me.  You do whatever you want.

The variable is volatile because the register changes outside the code. Each bit in this register gives the status of a specific key.  Thus, we want a header file so that we can access all the different bits with simple variable names.  Here we go:

//keypad.h
#ifndef __KEYPAD__
#define __KEYPAD__
#define KEYA             1
#define KEYB             2
#define KEYSELECT        4
#define KEYSTART         8
#define KEYRIGHT         16
#define KEYLEFT          32
#define KEYUP            64
#define KEYDOWN          128
#define KEYR             256
#define KEYL             512
 
//This is already in gba.h, but it has a much less reader-friendly name (REG_P1)
#define KEYS             (*(volatile u16*)0x4000130)
 
#define KEY_DOWN(k)       ( ! ( ( KEYS ) & k ) )
 
#endif

That’s the entire file. Now to check if a specific button is pressed, we check that  respective bit (using &) to see if it is clear. If so, the key has been pressed. Look at this:

if ( ! ( (KEYS) & DESIREDKEY ) )
{
  //The ! makes sure the bit is NOT 1… if it’s not 1, the key is pressed
  //do whatever
}

I prefer to make a little macro like this:

#define KEY_DOWN( k ) ( ! ( ( KEYS ) & k ) )

Then I can just use KEY_DOWN in my if statement instead of remember the & and ! of KEYS.

So, with the help of keypad.h, all you have to do is use KEY_DOWN to figure out if a button was pressed.





Next : Example