Skip to content

Instantly share code, notes, and snippets.

@futureshocked
Created March 7, 2022 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save futureshocked/b83fb9364d77cce292e90b7873f4389b to your computer and use it in GitHub Desktop.
Save futureshocked/b83fb9364d77cce292e90b7873f4389b to your computer and use it in GitHub Desktop.
This script implements a flight controller joystick for my X-Flight simulator. Works with an Arduino Micro or A-Star 32U4 Mini
// Requires Arduino Joystick Library https://github.com/MHeironimus/ArduinoJoystickLibrary
#include <Joystick.h>
const int8_t sw_1 = 18;
const int8_t sw_2 = 4;
const int8_t sw_3 = 6;
//Joystick_ Joystick;
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,
JOYSTICK_TYPE_JOYSTICK, 4, 0,
true, true, false, false, false, false,
true, true, true, false, true);
int pot0;
int pot1;
int pot2;
int pot3;
int pot4;
int pot5;
int currentSwState1;
int lastSwState1;
int currentSwState2;
int lastSwState2;
int currentSwState3;
int lastSwState3;
// roll pot0 A5 653 303
// pitch pot1 a4 0 915
// throttle pot2 a3 465 158
// mix pot3 a2 457 156
// flap pot4 a1 455 156
// rudder a8 374 960
void setup() {
Serial.begin(9600);
pinMode(sw_1, INPUT_PULLUP);
pinMode(sw_2, INPUT_PULLUP);
pinMode(sw_3, INPUT_PULLUP);
// Initialize Joystick Library
Joystick.begin();
Joystick.setXAxisRange(653, 303);
Joystick.setYAxisRange(0, 915);
Joystick.setThrottleRange(465, 158);
Joystick.setAcceleratorRange(457, 156);
Joystick.setRudderRange(374, 960);
Joystick.setSteeringRange(455, 156);
}
void loop() {
// Read Joystick
pot0 = analogRead(A5);
pot1 = analogRead(A4);
pot2 = analogRead(A3);
pot3 = analogRead(A2);
pot4 = analogRead(A1);
pot5 = analogRead(A8);
Serial.print(pot0);
Serial.print(" ");
Serial.print(pot1);
Serial.print(" ");
Serial.print(pot2);
Serial.print(" ");
Serial.print(pot3);
Serial.print(" ");
Serial.print(pot4);
Serial.print(" ");
Serial.print(pot5);
int currentSwState1 = !digitalRead(sw_1); // Button 1
if (currentSwState1 != lastSwState1)
{
Joystick.setButton(1, currentSwState1);
lastSwState1 = currentSwState1;
}
Serial.print(" ");
Serial.print(lastSwState1);
int currentSwState2 = !digitalRead(sw_2); // Button 2
if (currentSwState2 != lastSwState2)
{
Joystick.setButton(2, currentSwState2);
lastSwState2 = currentSwState2;
}
Serial.print(" ");
Serial.print(lastSwState2);
int currentSwState3 = !digitalRead(sw_3); // Button 3
if (currentSwState3 != lastSwState3)
{
Joystick.setButton(3, currentSwState3);
lastSwState3 = currentSwState3;
}
Serial.print(" ");
Serial.println(lastSwState3);
// Output Controls
Joystick.setXAxis(pot0);
Joystick.setYAxis(pot1);
Joystick.setThrottle(pot2);
Joystick.setAccelerator(pot3);
Joystick.setSteering(pot4);
Joystick.setRudder(pot5);
Joystick.sendState();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment