MHeironimus / ArduinoJoystickLibrary

An Arduino library that adds one or more joysticks to the list of HID devices an Arduino Leonardo or Arduino Micro can support.
GNU Lesser General Public License v3.0
2.06k stars 403 forks source link

How to setup joystick in setup() instead of top of code #288

Closed ZombieNoSleep closed 3 months ago

ZombieNoSleep commented 3 months ago

I am wanting the user to be able to setup/calibrate controller in setup(), but I see that I have to declare after the #include up top before setup() like: Joystick_ Joystick1(0x03,JOYSTICK_TYPE_GAMEPAD,1,0,true,true,false,false,false,false,false,false,false,false,false);

but i need a way to include that configuration in setup() after user has selected joystick type, calibrated (for other controller types) etc, before the Joystick1.begin(); but if I do it there I get "Joystick1' was not declared in this scope" error

Anyway around this? Thanks

spaelectronics commented 3 months ago

Did you solve this problem? If so, what was the solution?

ZombieNoSleep commented 3 months ago

Decided it was best to just include before setup(), and combine multiple joysticks into each joystick element as memory usage with adding more of them adds up fast. However, I did some testing and figured out how to declare them later on in the code like in a function called in setup().

Basically you need to use pointers, before setup() you will have just an array

Joystick_* Joystick[maxnumberofjoysticks];

and then anywhere else in code you can do this to set it up:

Joystick[0] = new Joystick_(0x03,1,0, etc);

When doing that, you have to continue using pointers on the joystick functions as well like:

Joystick[0]->setXAxisRange(-1,1);

Basically replacing the "." with "->" for the pointers

One of the problems with doing it this way (along with not seeing memory used in IDE when adding joysticks) is that when the USB is connected to the computer and the joysticks aren't setup yet in the code, it will not work. The only way I found to make it work is to include a library at top of code:

include <avr/io.h>

and write a function, that is called after you setup the joysticks to reset the USB connection itself:

void usbreset() { UDCON = (1 << DETACH); //disable USB device controller delay(100); //better to have a while loop waiting for detach, but could not get to work UDCON &= ~(1 << DETACH); //re-enable USB device controller delay(100); }

Still testing but both ways seem to work okay, although may not be the best solutions, still a noob at this stuff

ZombieNoSleep commented 3 months ago

Let me know if that helps and feel free to add to or give advice on it as well if you find better ways

GrumpyGopher commented 2 months ago

Really appreciate this post I was wanting to add controllers as needed and the usbreset allowed me to get it done. Works great with Windows. I still cannot get it to recognize more than 1 controller in Android but not sure there is a way to get around that.

Thanks