Teensy 4.1 Physical Pins and Joystick Buttons

I have a Teensy 4.1 and I'm using the 'Flight Sim Controls+ Joystick' USB type. My sketch has the number of buttons set to 32 and I will also be using 1x analog input.

My question is, how can I define which joystick buttons are mapped to which physical pin? Unfortunately I can't work with the default button to pin config as it creates layout issues for the PCB I am designing to accomodate everything.

Any help will be greatly appreciated.
 
It is up to your sketch to define the mapping. If you look at the example joystick complete example you see code like:
Code:
for (int i=0; i<numButtons; i++) {
    if (digitalRead(i)) {
      // when a pin reads high, the button is not pressed
      // the pullup resistor creates the "on" signal
      allButtons[i] = 0;
    } else {
      // when a pin reads low, the button is connecting to ground.
      allButtons[i] = 1;
    }
    Joystick.button(i + 1, allButtons[i]);
  }

Which is simply using the pin number the same as the index of the for loop,

You could instead change it like:

static const uint8_t button_pins[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
...
Code:
  for (int i=0; i<numButtons; i++) {
    if (digitalRead(button_pins[i])) {
      // when a pin reads high, the button is not pressed
      // the pullup resistor creates the "on" signal
      allButtons[i] = 0;
    } else {
      // when a pin reads low, the button is connecting to ground.
      allButtons[i] = 1;
    }
    Joystick.button(i + 1, allButtons[i]);
  }
Which has the same mappings currently, but you could change that array to use whatever pins you wish to use...
 
It is up to your sketch to define the mapping. If you look at the example joystick complete example you see code like...

Thanks very much for that, all I needed was a point in the right direction and all is working perfectly now. I've never worked with arrays before and I'm fairly new to Arduino, so I'm learning as I go. I'm also new to this forum so I appreciate the super quick reply as well.

I managed to figure out for myself that I needed to change ..
Code:
  for (int i=0; i<numButtons; i++) {
    pinMode(i, INPUT_PULLUP);
  }
to ..
Code:
  for (int i=0; i<numButtons; i++) {
    pinMode(button_pins[i], INPUT_PULLUP);
  }

.. in order to define the pins specified in my array as inputs with pullup resistors. Being able to set the order of the buttons by the order of the array was an added bonus too.

Once again, many many thanks.
 
Back
Top