KRITSADA

Clone PS2X library with Cute Function isCloseTo

Dec 12th, 2016
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //"ชอบรูปแบบการเขียนฟังก์ชั่น isCloseTo() จึงขอเก็บบันทึกเอาไว้"
  2. #include <PS2X_lib.h>  //for v1.6
  3.  
  4. PS2X ps2x; // create PS2 Controller Class
  5. int ly, lx, ry, rx;
  6.  
  7. //right now, the library does NOT support hot pluggable controllers, meaning
  8. //you must always either restart your Arduino after you conect the controller,
  9. //or call config_gamepad(pins) again after connecting the controller.
  10. int error = 0;
  11. byte type = 0;
  12. byte vibrate = 0;
  13. int lastReadings[] = {0, 0, 0, 0};
  14.  
  15. void setup(){
  16.  Serial.begin(9600);
  17.  
  18.  error = ps2x.config_gamepad(9,11,10,12, true, true);  
  19.  //setup pins and settings:  GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
  20.  
  21.  if(error == 0){
  22.    Serial.println("Found Controller, configured successful");
  23.    Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;");
  24.   Serial.println("holding L1 or R1 will print out the analog stick values.");
  25.   Serial.println("Go to www.billporter.info for updates and to report bugs.");
  26.  }
  27. }
  28.  
  29. void loop(){
  30.  if(error == 1) //skip loop if no controller found
  31.   return;
  32.  
  33.   ps2x.read_gamepad(false, vibrate);          //read controller and set large motor to spin at 'vibrate' speed
  34.  
  35.   // Update joystick values
  36.   ly = ps2x.Analog(PSS_LY);
  37.   lx = ps2x.Analog(PSS_LX);
  38.   ry = ps2x.Analog(PSS_RY);
  39.   rx = ps2x.Analog(PSS_RX);
  40.  
  41.   // If joystick values are reasonably close together (not too far from the last reading, as they would be if they were outliers,
  42.   // print out the values (effectively filtering out outliers)
  43.   if(isCloseTo(ly, lastReadings[0]) &&
  44.     isCloseTo(lx, lastReadings[1]) &&
  45.     isCloseTo(ry, lastReadings[2]) &&
  46.     isCloseTo(rx, lastReadings[3])) {
  47.     Serial.print("Stick Values:");
  48.     Serial.print(ly, DEC); //Left stick, Y axis. Other options: LX, RY, RX  
  49.     Serial.print(",");
  50.     Serial.print(lx, DEC);
  51.     Serial.print(",");
  52.     Serial.print(ry, DEC);
  53.     Serial.print(",");
  54.     Serial.println(rx, DEC);  
  55.   }
  56.  
  57.   // Populate our array with the last set of readings
  58.   lastReadings[0] = ly;
  59.   lastReadings[1] = lx;
  60.   lastReadings[2] = ry;
  61.   lastReadings[3] = rx;
  62.  
  63.   delay(10);  
  64. }
  65.  
  66. // Determines if two numbers are close together; returns true if they are, returns false if they're too far apart (difference in readings >= 50)
  67. boolean isCloseTo(int x, int y) {
  68.   return abs(x - y) < 50;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment