Thursday, 3 September 2015

Using XBox One Controller for command input

One of my requirements was to achieve fully autonomous flight. It dawned to me that before I get there, I'll probably need to manually control the quad to perform flight tests and improve the control subsystems. Hence I need a controller, but I don't want to invest in a costly radio-controlled solution.

I already have WiFi onboard the Pi. I have an Xbox One Controller. And I already need to develop a control app to run on my computer. I'll simply interface with the Xbox One controller, which is extremely versatile.


The control mapping will surely change, but it could look like the above.
  • Throttles: control motor throttle in manual mode, control altitude in altitude stabilization mode
  • Select: switch between manual, altitude stabilized, position hold and fully automated
  • Start: start/stop onboard control
  • Right joystick: adjust yaw
  • Left joystick: adjust pitch (up / down) and roll (left / right)
  • A-button: automated lift-off and landing activation
The controller can be plugged into any Windows system with a USB cord and is instantaneously recognized. Plus there are DirectX APIs to interface with it. Since I'll be developing in C# on the Windows side, I'll be using the SharpDX.XInput library, a convenient managed wrapper around the DX native XInput APIs.

I'm using Visual Studio Community 2015. In the package manager consoler, install the latest beta version of SharpDX.XInput
Install-Package SharpDX.XInput -Pre
I'm using the beta version as the latest stable release is based on DX11 and I ended up with missing DX DLLs (Windows 10 comes with DX12).

Once you have that imported, getting a Controller object is quite simple.. In the example below, in a simple Form app, when I update the text field with the X/Y coordinates of the left joystick anytime the form button is pressed.

using SharpDX.XInput;

namespace QuadRemote
{
    public partial class Form1 : Form
    {
        public Controller _controller;

        public Form1()
        {
            InitializeComponent();
            _controller = new Controller(SharpDX.XInput.UserIndex.One);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (_controller.IsConnected)
            {
                var state = _controller.GetState();
                var x = state.Gamepad.LeftThumbX;
                var y = state.Gamepad.LeftThumbY;

                richTextBox1.Text = x.ToString() + " " + y.ToString();
            }
        }
    }
}

No comments: