Skip to content

Instantly share code, notes, and snippets.

@careyi3
Created July 5, 2022 15:24
Show Gist options
  • Save careyi3/6194ea86bb99fc2e73a434060feb812d to your computer and use it in GitHub Desktop.
Save careyi3/6194ea86bb99fc2e73a434060feb812d to your computer and use it in GitHub Desktop.
Sample code for a nice abstraction layer around the excellent PsxNewLib for interfacing a PS2 controller with an Arduino.
#include <DigitalIO.h>
#include <PsxControllerHwSpi.h>
const byte PIN_PS2_ATT = 10;
PsxControllerHwSpi<PIN_PS2_ATT> psx;
boolean connected = false;
byte lxOld, lyOld, rxOld, ryOld;
PsxButtons oldButtons;
void callback1()
{
Serial.println("callback 1");
}
void callback2()
{
Serial.println("callback 2");
}
void stickCallback(byte x, byte y)
{
Serial.print(x);
Serial.print(",");
Serial.println(y);
}
void noOp()
{
}
void (*buttonCallbacks[16])() = {
callback1, // Select
callback2, // L3
noOp, // R3
noOp, // Start
noOp, // Up
noOp, // Right
noOp, // Down
noOp, // Left
noOp, // L2
noOp, // R2
noOp, // L1
noOp, // R1
noOp, // Triangle
noOp, // Circle
noOp, // Cross
noOp // Square
};
void (*stickCallbacks[2])(byte x, byte y) = {
stickCallback, // left
stickCallback, // right
};
void setup()
{
delay(300);
Serial.begin(115200);
}
void loop()
{
if (!connected)
{
config();
}
else
{
if (!psx.read())
{
Serial.println("Disconnected");
connected = false;
}
else
{
readController();
}
}
delay(16);
}
void readController()
{
PsxButtons buttons = psx.getButtonWord();
if (oldButtons != buttons)
{
bool buttonState[16];
oldButtons = buttons;
for (int i = 0; i < 16; i++)
{
if (buttons & 1)
{
buttonState[i] = true;
}
else
{
buttonState[i] = false;
}
buttons >>= 1;
}
handleButtonChange(buttonState);
}
byte lx, ly;
psx.getLeftAnalog(lx, ly);
if (lx != lxOld || ly != lyOld)
{
handleLeftAnalogChange(lx, ly);
lxOld = lx;
lyOld = ly;
}
byte rx, ry;
psx.getRightAnalog(rx, ry);
if (rx != rxOld || ry != ryOld)
{
handleRightAnalogChange(rx, ry);
rxOld = rx;
ryOld = ry;
}
}
void handleButtonChange(bool buttonState[])
{
for (int i = 0; i < 16; i++)
{
if (buttonState[i])
{
(*buttonCallbacks[i])();
}
}
}
void handleLeftAnalogChange(byte lx, byte ly)
{
(*stickCallbacks[0])(lx, ly);
}
void handleRightAnalogChange(byte rx, byte ry)
{
(*stickCallbacks[1])(rx, ry);
}
void config()
{
if (psx.begin())
{
Serial.println("Connected");
delay(300);
if (!psx.enterConfigMode())
{
Serial.println("Cannot enter config mode");
}
else
{
if (!psx.enableAnalogSticks())
{
Serial.println("Cannot enable analog sticks");
}
if (!psx.enableAnalogButtons())
{
Serial.println("Cannot enable analog buttons");
}
if (!psx.exitConfigMode())
{
Serial.println("Cannot exit config mode");
}
}
connected = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment