Thx for the heads up it took a cup of coffee and came up with this
#include <USBJoystick.h>
#include "mbed.h"
// Direct pin access for faster performance (no digitalRead/digitalWrite)
#define BUTTON_PIN(port, pin) ((volatile uint32_t*)(port + pin))
USBJoystick joystick;
// Define the button pins (1 to 33)
int pushButton[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 51, 50, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
// Define the hat switch pins (34 to 42)
int hatPins[9] = {34, 35, 36, 37, 38, 39, 40, 41, 42};
// Variable to store button state as 32-bit value
uint32_t buttons = 0;
// Variable to store hat switch state
uint8_t hat = 8; // Set initial state to neutral position (8)
// Analog pins for joystick movement and throttle
int y = A0;
int x = A1;
int z = A2;
int q = A3;
void setup() {
// Initialize button pins with internal pull-ups
for (int i = 0; i < 32; i++) {
pinMode(pushButton[i], INPUT_PULLUP); // Activate internal pull-up resistors
}
// Initialize hat switch pins with internal pull-ups
for (int i = 0; i < 9; i++) {
pinMode(hatPins[i], INPUT_PULLUP); // Activate internal pull-up resistors
}
}
void loop() {
// Update joystick axes (movement and throttle)
joystick.move(analogRead(x), analogRead(y));
joystick.throttle(analogRead(z));
joystick.rudder(analogRead(q));
// Check button states and update the button binary pattern
buttons = 0; // Reset the button state to 0 (all buttons not pressed)
// Direct bit manipulation for faster button checks
for (int i = 0; i < 32; i++) {
if (!digitalRead(pushButton[i])) { // LOW means button pressed, due to pull-ups
buttons |= (1 << i); // Set the corresponding button bit to 1 if pressed
}
}
// Update joystick button state with the current button binary value
joystick.buttons(buttons);
// Check hat switch state and determine its position
hat = 8; // Default to neutral position (no direction pressed)
// Use direct bit manipulation for hat switch
for (int i = 0; i < 9; i++) {
if (!digitalRead(hatPins[i])) {
hat = i + 1; // Map to hat values (1 to 8)
break; // Exit the loop once a direction is detected
}
}
// Update joystick hat state with the current hat value
joystick.hat(hat);
// Update joystick state
joystick.update();
}