Skip to content

Instantly share code, notes, and snippets.

@andsve
Created January 16, 2021 14:32
Show Gist options
  • Save andsve/3342bab28de5b0d2a793303faadabd37 to your computer and use it in GitHub Desktop.
Save andsve/3342bab28de5b0d2a793303faadabd37 to your computer and use it in GitHub Desktop.
snippets for reading nes controller 1 input (using minifb)
// ...
enum GAMEPAD_ID
{
GAMEPAD_1 = 0,
GAMEPAD_2 = 1,
GAMEPAD_MAX = GAMEPAD_2,
};
enum GAMEPAD_BUTTON
{
GAMEPAD_A = 0,
GAMEPAD_B = 1,
GAMEPAD_SELECT = 2,
GAMEPAD_START = 3,
GAMEPAD_UP = 4,
GAMEPAD_DOWN = 5,
GAMEPAD_LEFT = 6,
GAMEPAD_RIGHT = 7,
};
struct sys_t
{
// ...
uint8_t gamepad_readbit;
uint8_t gamepad[2];
// ...
};
// ...
// ...
// handle register writes
inline unsigned char handle_memmap_reg_write(cpu_t &cpu, unsigned short addr, unsigned short data, bool *handled)
{
// ...
} else if (addr == 0x4016 || addr == 0x4017) {
*handled = true;
// todo need to check that it was bit 0 that was set??
sys.gamepad_readbit = 0;
}
// ...
}
// ...
// handles register reads
inline unsigned char handle_memmap_reg_read(cpu_t &cpu, unsigned short addr, bool *handled, bool peek = false)
{
// ...
} else if (addr == 0x4016 || addr == 0x4017) {
*handled = true;
uint8_t gamepad_id_to_read = addr == 0x4016 ? 0 : 1;
uint8_t data = (sys.gamepad[gamepad_id_to_read] >> sys.gamepad_readbit) & 0x1;
sys.gamepad_readbit++;
sys.gamepad_readbit = sys.gamepad_readbit % 8; // roll back to zero if going over 7
return data | 0x40;
}
// ...
}
// ...
// ...
// callback from when the window gets input
static void minifb_keyboard_cb(struct mfb_window *window, mfb_key key, mfb_key_mod mod, bool isPressed)
{
neeze::sys_t* sysp = (neeze::sys_t*)mfb_get_user_data(window);
// printf("%s %x\n", isPressed ? "PRESSED" : "RELEASED", key);
switch (key) {
case KB_KEY_ENTER:
neeze::set_input(*sysp, neeze::GAMEPAD_1, neeze::GAMEPAD_START, isPressed);
break;
case KB_KEY_SPACE:
neeze::set_input(*sysp, neeze::GAMEPAD_1, neeze::GAMEPAD_SELECT, isPressed);
break;
case KB_KEY_Z:
neeze::set_input(*sysp, neeze::GAMEPAD_1, neeze::GAMEPAD_A, isPressed);
break;
case KB_KEY_X:
neeze::set_input(*sysp, neeze::GAMEPAD_1, neeze::GAMEPAD_B, isPressed);
break;
case KB_KEY_LEFT:
neeze::set_input(*sysp, neeze::GAMEPAD_1, neeze::GAMEPAD_LEFT, isPressed);
break;
case KB_KEY_RIGHT:
neeze::set_input(*sysp, neeze::GAMEPAD_1, neeze::GAMEPAD_RIGHT, isPressed);
break;
case KB_KEY_UP:
neeze::set_input(*sysp, neeze::GAMEPAD_1, neeze::GAMEPAD_UP, isPressed);
break;
case KB_KEY_DOWN:
neeze::set_input(*sysp, neeze::GAMEPAD_1, neeze::GAMEPAD_DOWN, isPressed);
break;
default:
break;
}
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment