Controlling Arduino with a USB Joystick

By markvillacampa on January 23, 2012 — 1 min read

In a previous post I explained
how to talk to Arduino through the serial port. Now taking advantage of this usb-to-serial interface we’re going to send instructions to Arduino using a USB Joystick. Any Playstation-like controller or Xbox 360 controller with a USB receiver will work. However if you’re on Mac you will need this
drivers for the Xbox 360 controller.

Since I used Ruby in the previous post, I wanted to use Ruby for getting the joystick input in order to write a cleaner script. I found
Rubygame to be the best option. It’s a Ruby framework for game developers, inspired in
Pygame (the same thing but written in Python) which is a wrapper of the SDL library. The
documentation is pretty good.

There are several ways to install Rubygame. The easiest one for Mac is to install it using
Homebrew. Once you have installed Homebrew run this to install Rubygame’s dependencies:

sudo brew install sdl

sudo brew install sdl_gfx sdl_image sdl_mixer sdl_ttf

Then install Rubygame:

gem install rubygame

From now on, I suppose you have a working Ruby to serial port working as I explained in a
previous post.

Now plug in your Arduino and Joystick and run this Ruby script:#!/usr/bin/env ruby

require 'rubygems'
require 'rubygame'
require 'serialport'

# You should change the name of the port Arduino is connected. You can find it in the Tools > Serial Port in the Arduino IDE
sp = "/dev/YOUR_ARDUINO_PORT", 9600

# Start the queue of events
@event_queue =

# Initialize the Joystick in the first position (0)

while event = @event_queue.wait
  # Output the info of the event
  p event
  # If a button pressed event is detected, and the button is the number "1" or "2" then we do write to the serial port
  if event.is_a? Rubygame::Events::JoystickButtonPressed
    case event.button
        when 1
            sp.write 1
        when 2
            sp.write 0

If you press any button you should see a stream of events in the terminal. Mapping the numbers of the buttons is a bit tricky because it will probably change in your joystick, but the button number “1” should turn ON the led in the pin number 13 of your Arduino, and the button number “2” should turn it OFF.

Now you can build you own joystick controlled robot 😉 feel free to ask any doubts.