Advertisement
Guest User

Arduino STM32 mini Joystick

a guest
Sep 19th, 2019
893
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <USBComposite.h>
  2. #define PIN_X PA0
  3. #define PIN_Y PA1
  4. #define BUTTONS 6 // Number of buttons
  5.  
  6. uint8_t button_pins[BUTTONS] = {PB11,PB10,PB1,PB0,PA7,PA6};
  7. // mapping to gamepad buttons
  8. uint8_t button_mapping[BUTTONS] = {9,13,15,14,10,16};
  9.  
  10. // Calibration values
  11. // Check initial values without map-constrain and tweak until satisfied
  12. const int16_t x_offset = 2300 / 2;
  13. const int16_t x_low = 800    - x_offset;
  14. const int16_t x_high = 3731  - x_offset;
  15.  
  16. const int16_t y_offset = 1750 / 2;
  17. const int16_t y_low = 520    - y_offset;
  18. const int16_t y_high = 3338  - y_offset;
  19.  
  20. USBXBox360 XBox360;
  21.  
  22. void setup() {
  23.   pinMode(PIN_X, INPUT_ANALOG);
  24.   pinMode(PIN_Y, INPUT_ANALOG);
  25.   for(int i = 0;i<BUTTONS;i++){
  26.     pinMode(button_pins[i], INPUT_PULLUP);
  27.   }
  28.   // Send manually reports every run and not on every change
  29.   XBox360.setManualReportMode(true);
  30.   XBox360.begin();
  31.   delay(1000);
  32. }
  33.  
  34. void loop() {
  35.   int16_t x_val = analogRead(PIN_X);
  36.   int16_t y_val = analogRead(PIN_Y);
  37.  
  38.   // comment these out to disable scaling for calibration
  39.   x_val = map(constrain(x_val-x_offset,x_low,x_high),x_low,x_high,-0x7fff,0x7fff);
  40.   y_val = map(constrain(y_val-y_offset,y_low,y_high),y_low,y_high,-0x7fff,0x7fff);
  41.  
  42.   XBox360.X(x_val);
  43.   XBox360.Y(y_val);
  44.  
  45.   //Map sliders to half y axes for racing games
  46.   XBox360.sliderRight(constrain(y_val>>7,0,255));
  47.   XBox360.sliderLeft(constrain(-(y_val>>7),0,255));
  48.  
  49.   for(int i = 0;i<BUTTONS;i++){
  50.     XBox360.button(button_mapping[i],!digitalRead(button_pins[i]));
  51.   }
  52.  
  53.   XBox360.send(); // Send report
  54.   delay(1);
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement