Библиотека джойстика для ардуино

Arduino и джойстик

Описание

Джойстик – орган управления с двумя аналоговыми осями (X и Y) и одной кнопкой. Отлично подходит для управления в играх, а также некоторыми механизмами

Подключение

Подключается к питанию, аналоговые оси (VRX и VRY) – на аналоговые пины, кнопка SW – на цифровой пин. Кнопка никуда не подтянута, но это можно сделать средствами микроконтроллера. Джойстик удобнее подключать проводами папа-мама к макетке:

Примеры

Опросим обе оси джойстика и кнопку (умножим на 100 для лучшего масштаба) и выведем значения в порт через запятую. Подвигаем джойстиком, пощёлкаем кнопкой, посмотрим на график:

Оси джойстика ожидаемо выдают значение от 0 до 1023, а кнопка – инвертирована, так как при нажатии замыкается на GND. Работать с сырыми данными с джойстика не очень удобно, потому что нет “нуля”: он находится где-то в районе 500. Можно попробовать сделать по простому, через функцию map() . Преобразуем значения с осей в диапазон -100.. 100:

В принципе стало удобнее, с такими значениями гораздо удобнее работать

Библиотека

Для более удобной работы с джойстиком можно использовать библиотеку GyverJoy. Она позволяет удобно калибровать джойстик, задавать мёртвую зону и плавность изменения значений. Подробное описание и примеры можно найти по ссылке выше.

Источник

YukMingLaw/ArduinoJoystickWithFFBLibrary

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

Readme.md

Arduino Joystick With Force Feedback Library

This is a joy library for Atmega32UX chip with force feedback, which can be used to make game handle with vibration, game steering wheel with force feedback, etc.Multi-axis-force-feedback feature is added.

0. example: examples/JoystickWithFFB/JoystickWithFFB.ino

1. create JoyStick object

params describe
REPORT_ID Hid report id
JOYSTICK_TYPE Type of devece:JOYSTICK,GAMEPAD,MULTI_AXIS
button count [0-32]
Hat Switch count [0,1,2]
X Axis enable True or False
Y Axis enable True or False
Z Axis enable True or False
Rx Axis enable True or False
Ry Axis enable True or False
Rz Axis enable True or False
Rudder enable True or False
Throttle enable True or False
Accelerator enable True or False
Brake enable True or False
Steering enable True or False

Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_JOYSTICK,8, 0,false, true,true,false, false, false,false, false,false, false, false);

2. After the object is created, the x-axis and y-axis are bound as the force feedback axis by default.The gains of various forces effect are set through the struct and the interface as following:

3.Set the parameters of spring effect, damper effect, inertia effect and friction effect through the struct and the interface as following:

4.Finally,get the force value with

params int32_t* forces is an int32 array of length 2

forces[0] is the X-Axis force data

forces[1] is the Y-Axis force data

return type void

Pay Attention!

Joystick.setGains(mygains) and Joystick.setEffectParams(myeffectparams) must be invoked before JoyStick.getForce(int32_t* forces)

This library is based on Heironimus and hoantv ‘s work,very grateful for their work.

About

An Arduino Joystick Library With Force Feedback Feature

Источник

tremaru/iarduino_I2C_Joystick

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This is a library for Arduino IDE. It allows to work with Joystick module made by iArduino.ru

Данная библиотека для Arduino IDE позволяет работать с модулем Джойстик от iArduino.ru

Подробнее про установку библиотеки читайте в нашей инструкции.

Подключаем библиотеку

Создаём объект

Инициализация работы

Изменение адреса модуля

Перезагрузка модуля

Получение текущего адреса

Получение версии прошивки

Запрос текущей X координаты

Запрос текущей Y координаты

Запрос текущих координат

Запрос значений АЦП оси X

Запрос значений АЦП оси Y

Запрос значений АЦП

Получение состояний кнопки

Калибровка координат X

Калибровка координат Y

Запрос калибровочных значений X

Запрос калибровочных значений Y

Установка мертвой зоны

Установка усреднения показаний

About

Библиотека iarduino_I2C_Joystick для Trema модуля — Джойстик, I2C-flash

Источник

edumardo/Joystick

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Dual-axis XY Joystick library for Arduino

Just a simple arduino library for control a dual axis joystick. Main features:

  • You can map outputs into a custom range through the constructor.
  • You can define a threshold to control where axis movement don´t have effect.
  • You can invert the axis values (in my hardware Y-axis decreases when I push forward the joystick).

Install the library & Import

Download this repository as a .zip file and from the Arduino IDE go to Sketch -> Include library -> Add .ZIP Library.

You can import the library in your code using the Arduino IDE going to Sketch -> Include library -> Joystick or directly writing the include statement in your code:

A standar analog read is [0,1023]. In the constructor you set your preferences: [0,255], [-127,127], etc.

No action limit

The library defines a threshold, called no action limit, where you can control that axis movement don’t have effect. According with your joystick hardware, you will want to increase/reduce the value. Hence, there are a low and high limit when the movement of the joystick has no effect.

Some hardware, like I have, Y-axis decreases when I push forward. So you can control this issue inverting range values. With every invocation you reverse the axis.

Using the library

In examples/testJoystickLibrary.ino you can see the library in action.

First, initialize a Joystick object with the proper pins,no action limit and map range:

Invert the axis if your hardware needs it:

Then, get the outputs of the joystick and the defined thresholds:

Ultimatelty, do something, like control the direction with threshold:

NOTE: with every invocation of the getters, you will read the joystick status.

About

Just a simple arduino library to control a dual axis Joystick.

Источник

Библиотека джойстика для ардуино

Arduino Joystick Library

This library can be used with Arduino IDE 1.6.6 or above (see Wiki — Testing Details for more information) to add one or more joysticks (or gamepads) to the list of HID devices an Arduino Leonardo or Arduino Micro (or any Arduino clone that is based on the ATmega32u4) can support. This library will also work with the Arduino Due, thanks to @Palakis. A complete list of supported boards can be found in the Wiki — Supported Boards. This will not work with Arduino IDE 1.6.5 (or below) or with non-32u4 based Arduino devices (e.g. Arduino UNO, Arduino MEGA, etc.).

The joystick or gamepad can have the following features:

  • Buttons (default: 32)
  • Up to 2 Hat Switches
  • X, Y, and/or Z Axis (up to 16-bit precision)
  • X, Y, and/or Z Axis Rotation (up to 16-bit precision)
  • Rudder (up to 16-bit precision)
  • Throttle (up to 16-bit precision)
  • Accelerator (up to 16-bit precision)
  • Brake (up to 16-bit precision)
  • Steering (up to 16-bit precision)

The following instructions can be used to install the latest version of the library in the Arduino IDE (thanks to @per1234 for this update):

  1. Download https://github.com/MHeironimus/ArduinoJoystickLibrary/archive/master.zip
  2. In the Arduino IDE, select Sketch > Include Library > Add .ZIP Library. . Browse to where the downloaded ZIP file is located and click Open . The Joystick library’s examples will now appear under File > Examples > Joystick .

The following example Arduino sketch files are included in this library:

  • JoystickButton — Creates a Joystick and maps pin 9 to button 0 of the joystick, pin 10 to button 1, pin 11 to button 2, and pin 12 to button 3.
  • JoystickKeyboard — Creates a Joystick and a Keyboard. Maps pin 9 to Joystick Button 0, pin 10 to Joystick Button 1, pin 11 to Keyboard key 1, and pin 12 to Keyboard key 2.
  • GamepadExample — Creates a simple Gamepad with an Up, Down, Left, Right, and Fire button.
  • FunduinoJoystickShield — Creates a simple Gamepad using a Funduino Joystick Shield (https://protosupplies.com/product/funduino-joystick-shield-v1-a/).
  • ArcadeStickExample — Simple arcade stick example that demonstrates how to read twelve Arduino Pro Micro digital pins and map them to the library (thanks to @nebhead for this example). NOTE: This sketch is for the Arduino Pro Micro only.

Used for Testing

  • JoystickTest — Simple test of the Joystick library. It exercises many of the Joystick library’s functions when pin A0 is grounded.
  • MultipleJoystickTest — Creates 4 Joysticks using the library (each with a slightly different configuration) and exercises the first 16 buttons (if present), the X axis, and the Y axis of each joystick when pin A0 is grounded.
  • FlightControllerTest — Creates a Flight Controller and tests 32 buttons, the X and Y axis, the Throttle, and the Rudder when pin A0 is grounded.
  • HatSwitchTest — Creates a joystick with two hat switches. Grounding pins 4 — 11 cause the hat switches to change position.
  • DrivingControllerTest — Creates a Driving Controller and tests 4 buttons, the Steering, Brake, and Accelerator when pin A0 is grounded.

Joystick Library API

The following API is available if the Joystick library in included in a sketch file.

Constructor used to initialize and setup the Joystick. The following optional parameters are available:

  • uint8_t hidReportId — Default: 0x03 — Indicates the joystick’s HID report ID. This value must be unique if you are creating multiple instances of Joystick. Do not use 0x01 or 0x02 as they are used by the built-in Arduino Keyboard and Mouse libraries.
  • uint8_t joystickType — Default: JOYSTICK_TYPE_JOYSTICK or 0x04 — Indicates the HID input device type. Supported values:
    • JOYSTICK_TYPE_JOYSTICK or 0x04 — Joystick
    • JOYSTICK_TYPE_GAMEPAD or 0x05 — Gamepad
    • JOYSTICK_TYPE_MULTI_AXIS or 0x08 — Multi-axis Controller
  • uint8_t buttonCount — Default: 32 — Indicates how many buttons will be available on the joystick.
  • uint8_t hatSwitchCount — Default: 2 — Indicates how many hat switches will be available on the joystick. Range: 0 — 2
  • bool includeXAxis — Default: true — Indicates if the X Axis is available on the joystick.
  • bool includeYAxis — Default: true — Indicates if the Y Axis is available on the joystick.
  • bool includeZAxis — Default: true — Indicates if the Z Axis (in some situations this is the right X Axis) is available on the joystick.
  • bool includeRxAxis — Default: true — Indicates if the X Axis Rotation (in some situations this is the right Y Axis) is available on the joystick.
  • bool includeRyAxis — Default: true — Indicates if the Y Axis Rotation is available on the joystick.
  • bool includeRzAxis — Default: true — Indicates if the Z Axis Rotation is available on the joystick.
  • bool includeRudder — Default: true — Indicates if the Rudder is available on the joystick.
  • bool includeThrottle — Default: true — Indicates if the Throttle is available on the joystick.
  • bool includeAccelerator — Default: true — Indicates if the Accelerator is available on the joystick.
  • bool includeBrake — Default: true — Indicates if the Brake is available on the joystick.
  • bool includeSteering — Default: true — Indicates if the Steering is available on the joystick.

The following constants define the default values for the constructor parameters listed above:

  • JOYSTICK_DEFAULT_REPORT_ID is set to 0x03
  • JOYSTICK_DEFAULT_BUTTON_COUNT is set to 32
  • JOYSTICK_DEFAULT_HATSWITCH_COUNT is set to 2

Starts emulating a game controller connected to a computer. By default, all methods update the game controller state immediately. If initAutoSendState is set to false , the Joystick.sendState method must be called to update the game controller state.

Stops the game controller emulation to a connected computer (Note: just like the Arduino Keyboard.h and Mouse.h libraries, the end() function does not actually do anything).

Joystick.setXAxisRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the X axis. Default: 0 to 1023

Sets the X axis value. See setXAxisRange for the range.

Joystick.setYAxisRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Y axis. Default: 0 to 1023

Sets the Y axis value. See setYAxisRange for the range.

Joystick.setZAxisRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Z axis. Default: 0 to 1023

Sets the Z axis value. See setZAxisRange for the range.

Joystick.setRxAxisRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the X axis rotation. Default: 0 to 1023

Sets the X axis rotation value. See setRxAxisRange for the range.

Joystick.setRyAxisRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Y axis rotation. Default: 0 to 1023

Sets the Y axis rotation value. See setRyAxisRange for the range.

Joystick.setRzAxisRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Z axis rotation. Default: 0 to 1023

Sets the Z axis rotation value. See setRzAxisRange for the range.

Joystick.setRudderRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Rudder. Default: 0 to 1023

Sets the Rudder value. See setRudderRange for the range.

Joystick.setThrottleRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Throttle. Default: 0 to 1023

Sets the Throttle value. See setThrottleRange for the range.

Joystick.setAcceleratorRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Accelerator. Default: 0 to 1023

Sets the Accelerator value. See setAcceleratorRange for the range.

Joystick.setBrakeRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Brake. Default: 0 to 1023

Sets the Brake value. See setBrakeRange for the range.

Joystick.setSteeringRange(int32_t minimum, int32_t maximum)

Sets the range of values that will be used for the Steering. Default: 0 to 1023

Sets the Steering value. See setSteeringRange for the range.

Joystick.setButton(uint8_t button, uint8_t value)

Sets the state ( 0 or 1 ) of the specified button (range: 0 — ( buttonCount — 1 )). The button is the 0-based button number (i.e. button #1 is 0 , button #2 is 1 , etc.). The value is 1 if the button is pressed and 0 if the button is released.

Press the indicated button (range: 0 — ( buttonCount — 1 )). The button is the 0-based button number (i.e. button #1 is 0 , button #2 is 1 , etc.).

Release the indicated button (range: 0 — ( buttonCount — 1 )). The button is the 0-based button number (i.e. button #1 is 0 , button #2 is 1 , etc.).

Joystick.setHatSwitch(int8_t hatSwitch, int16_t value)

Sets the value of the specified hat switch. The hatSwitch is 0-based (i.e. hat switch #1 is 0 and hat switch #2 is 1 ). The value is from 0° to 360°, but in 45° increments. Any value less than 45° will be rounded down (i.e. 44° is rounded down to 0°, 89° is rounded down to 45°, etc.). Set the value to JOYSTICK_HATSWITCH_RELEASE or -1 to release the hat switch.

Sends the updated joystick state to the host computer. Only needs to be called if AutoSendState is false (see Joystick.begin for more details).

See the Wiki for more details on things like FAQ, supported boards, testing, etc.

Источник

Adblock
detector