Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //"ชอบรูปแบบการเขียนฟังก์ชั่น isCloseTo() จึงขอเก็บบันทึกเอาไว้"
- #include <PS2X_lib.h> //for v1.6
- PS2X ps2x; // create PS2 Controller Class
- int ly, lx, ry, rx;
- //right now, the library does NOT support hot pluggable controllers, meaning
- //you must always either restart your Arduino after you conect the controller,
- //or call config_gamepad(pins) again after connecting the controller.
- int error = 0;
- byte type = 0;
- byte vibrate = 0;
- int lastReadings[] = {0, 0, 0, 0};
- void setup(){
- Serial.begin(9600);
- error = ps2x.config_gamepad(9,11,10,12, true, true);
- //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
- if(error == 0){
- Serial.println("Found Controller, configured successful");
- Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;");
- Serial.println("holding L1 or R1 will print out the analog stick values.");
- Serial.println("Go to www.billporter.info for updates and to report bugs.");
- }
- }
- void loop(){
- if(error == 1) //skip loop if no controller found
- return;
- ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed
- // Update joystick values
- ly = ps2x.Analog(PSS_LY);
- lx = ps2x.Analog(PSS_LX);
- ry = ps2x.Analog(PSS_RY);
- rx = ps2x.Analog(PSS_RX);
- // If joystick values are reasonably close together (not too far from the last reading, as they would be if they were outliers,
- // print out the values (effectively filtering out outliers)
- if(isCloseTo(ly, lastReadings[0]) &&
- isCloseTo(lx, lastReadings[1]) &&
- isCloseTo(ry, lastReadings[2]) &&
- isCloseTo(rx, lastReadings[3])) {
- Serial.print("Stick Values:");
- Serial.print(ly, DEC); //Left stick, Y axis. Other options: LX, RY, RX
- Serial.print(",");
- Serial.print(lx, DEC);
- Serial.print(",");
- Serial.print(ry, DEC);
- Serial.print(",");
- Serial.println(rx, DEC);
- }
- // Populate our array with the last set of readings
- lastReadings[0] = ly;
- lastReadings[1] = lx;
- lastReadings[2] = ry;
- lastReadings[3] = rx;
- delay(10);
- }
- // Determines if two numbers are close together; returns true if they are, returns false if they're too far apart (difference in readings >= 50)
- boolean isCloseTo(int x, int y) {
- return abs(x - y) < 50;
- }
Advertisement
Add Comment
Please, Sign In to add comment