for esp32

(basic) from the example

first include the lib

1
#include <PS2X_lib.h> 

define the pin

1
2
3
4
#define PS2_DAT        19  //MISO  19
#define PS2_CMD 23 //MOSI 23
#define PS2_SEL 5 //SS 5
#define PS2_CLK 18 //SLK 18

mode select

  • select modes of PS2 controller:
    • pressures = analog reading of push-butttons
    • rumble = motor rumbling 震动
  • uncomment 1 of the lines for each mode selection
1
2
#define pressures   false
#define rumble false

normal plan

1
2
3
4
5
6
7
8
9
10
PS2X ps2x; // create PS2 Controller Class

//right now, the library does NOT support hot pluggable controllers, meaning
//you must always either restart your Arduino after you connect the controller,
//or call config_gamepad(pins) again after connecting the controller.

int error = -1;
byte type = 0;
byte vibrate = 0;
int tryNum = 1;

initialization

1
2
3
4
5
6
7
8
while (error != 0) {
delay(1000);// 1 second wait
//setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble);
Serial.print("#try config ");
Serial.println(tryNum);
tryNum ++;
}

read the value plan

first
1
ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed
read
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//will be TRUE as long as button is pressed
// 长按
if(ps2x.Button(PSB_START))
Serial.println("Start is being held");


vibrate = ps2x.Analog(PSAB_CROSS); //this will set the large motor vibrate speed based on how hard you press the blue (X) button
if (ps2x.NewButtonState()) { //will be TRUE if any button changes state (on to off, or off to on)
if(ps2x.Button(PSB_L3))
Serial.println("L3 pressed");
if(ps2x.Button(PSB_R3))
Serial.println("R3 pressed");
if(ps2x.Button(PSB_L2))
Serial.println("L2 pressed");
if(ps2x.Button(PSB_R2))
Serial.println("R2 pressed");
if(ps2x.Button(PSB_TRIANGLE))
Serial.println("△ pressed");
}


//△□○×
if(ps2x.ButtonPressed(PSB_CIRCLE)) //will be TRUE if button was JUST pressed
Serial.println("○ just pressed");
if(ps2x.NewButtonState(PSB_CROSS)) //will be TRUE if button was JUST pressed OR released
Serial.println("× just changed");
if(ps2x.ButtonReleased(PSB_SQUARE)) //will be TRUE if button was JUST released
Serial.println("□ just released");