Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Poor-man's LEDBlinky with RetroPie and Pac-Drive

NOTE: This Gist was an early write-up of this blog post, part of what became an eleven-part series on my arcade cabinet. I'd suggest you read that post instead of this, but some of the comments on this Gist contain updates and field reports that you might find useful.

RetroPie, LED control, and you

I wanted LEDBlinky-style functionality out of my RetroPie cabinet. But I didn't need RGB control or magical frontend integration or anything like that. I had buttons with simple single-color LEDs.

I've got a simple control panel with six buttons per player. All I wanted was this:

  • When I launch Street Fighter 2, all twelve buttons should light up.
  • When I launch The Simpsons, only the first two buttons for each player should light up.
  • When I launch Pac-Man, none of the buttons should light up.

You get the idea.

Here's a demonstration in the form of a shaky video.

Here's how I did it.

Hardware

I got a Pac-Drive from Ultimarc. It's got 16 terminals for LEDs. 1–6 control Player 1's buttons; 7–12 control Player 2's buttons. The remaining four terminals got devoted to the start buttons (13 and 14), the coin buttons (both on 15), and four small buttons I use for functions (all on 16).

After all that's wired up, all you need is a single USB cable running to your Pi — or, even better, to a powered USB hub that is itself connected to the Pi. The LEDs get powered from USB.

Software

Most of the software for the Pac-Drive is meant for a Windows environment. After some digging, I found this third-party utility for Linux that allows for controlling a Pac-Drive from the command-line. It was exactly what I needed, though it was eight years old and took some wrangling to get installed on a Pi.

From a stock RPi with Raspbian Jessie, you'll need at least these packages:

sudo apt-get install libusb-dev build-essential

You'll also need libhid, which is hard to find because it's deprecated. There's no package for it in APT, the source code is behind a login for some reason, and then you've got to make a change to the source to get it to compile on the Pi. I solved all three problems by applying that fix and then putting up the fixed source on my server.

From your home directory:

mkdir src && cd src

wget "http://andrewdupont.net/pi/libhid-0.2.16.tar.gz"
tar xvzf libhid-0.2.16.tar.gz
cd libhid-0.2.16
./configure
make
sudo make install

Now we're ready to install the pacdrive utility.

cd ~/src
wget "http://www.zumbrovalley.net/pacdrive/dnld/pacdrive_0_2.tar.gz"
tar xvzf pacdrive_0_2.tar.gz
cd pacdrive_0_2
make

If you do make install it'll put the pacdrive binary in /usr/bin, though you can edit the Makefile beforehand to specify a different directory. I did neither; I just manually copied the pacdrive binary to /home/pi/bin. (If you do this, make sure you put /home/pi/bin in your PATH.)

Hooking into RetroPie

So now you can control the LEDs from the command line, but that doesn't help much.

How will it know which LEDs to light up for which game?

One option here would be to use something called controls.dat, which is a project for cataloguing the controls for most MAME games. (4-way joystick? 8-way? How many buttons? How many players? Hotseat, or does each player have their own controls? And so on.)

The problem with this approach is that (a) the controls.dat project is dormant; (b) there are lots of gaps in its database.

If you're anything like me, you don't need a comprehensive solution. I don't care how many buttons some random mah-jongg game uses because I'll never play it. I've got about 100 arcade games set up and I don't mind specifying their configs manually.

So here's what I came up with:

  1. Create a /home/pi/leds directory.
  2. Inside that directory, create another directory for each system you want to control. (I've got arcade and daphne; you might have others.)
  3. Inside each system's directory, define a text file whose name matches the name of the game. For instance: simpsons2p is the ROM name for the two-player version of The Simpsons, so I'd create a file called simpsons2p.cfg with these contents: 1, 2, 7, 8. In other words: light up buttons 1, 2, 7, and 8, and turn off all the other LEDs.

This way it's simple to define new configs and simple for RetroPie to know where to look for configs knowing only the system and the ROM name.

How will it light up the LEDs on game launch?

All emulator launches go through something called runcommand.sh. There's a new feature in RetroPie 4.x: the ability to define scripts called runcommand-onstart.sh and runcommand-onend.sh. These scripts will run before a game starts and after a game ends, respectively, and they receive some metadata, including the name of the system and the name of the game.

If you want to do it exactly how I did:

  1. cd /opt/retropie/configs/all
  2. nano runcommand-start.sh (shouldn't need sudo, but I might be wrong)
  3. Paste the contents of the runcommand-onstart.sh from this gist.
  4. Repeat steps 3 and 4 for runcommand-onend.sh.

These scripts reference two other scripts called led-start and led-end, which you should put in /home/pi/bin. This is completely overengineered, but it lets me define some buttons as "always on" without having to include them in every single config file. That happens in a file called /home/pi/.ledrc. Here's what mine looks like:

+13, +14, +15, +16

That means "always light up both start buttons, the coin buttons, and the small function buttons." You can read the source of led-start to learn more.

If you want to use these scripts, you'll need Ruby, which isn't installed by default on Raspbian Jessie. sudo apt-get install ruby2.1 should take care of it.

What if a game doesn't have a config? Well, if you followed these instructions to the letter, none of the buttons for either player will light up. That's fine with me, because I don't have any games without configs. You might want it to do something different in that situation.

Problems?

If this doesn't work, it's probably because I left something out. Leave a comment and we'll figure it out together.

#!/usr/bin/env ruby
# For now, let's just turn all LEDs back on.
exec(%Q[/home/pi/bin/pacdrive -a -q])
#!/usr/bin/env ruby
require 'optparse'
require 'pathname'
require 'pp'
$options = {
debug: false,
debug_path: '/home/pi/led_log.txt'
}
# Takes a string like "1,2,3,7,8,9" and determines which LEDs should be lit
# up. Shells out to the `pacdrive` binary to do it.
$usage = OptionParser.new do |opts|
opts.banner = "Usage: led-start [OPTIONS] system game"
opts.separator ""
opts.on('-d', '--debug', "Writes debug output to the specified file (defaults to ~/led_log.txt).") do |path|
$options[:debug] = true
$options[:debug_path] = path unless (path.nil? || path.empty?)
end
opts.on_tail('-h', '--help', "Displays this help message.")
end
$usage.parse!
# The path to the file that sets defaults for LED state. If no config is
# found for a certain game, this file ends up determining all states. If a
# game config omits a certain button, the default config can specify that
# that button should nonetheless be on. (This is useful for, e.g., coin
# buttons, aux buttons, and such. These should almost always be on, but it's
# dumb to have to specify them in every game config file.)
DEFAULT_CONFIG_PATH = Pathname.new('/home/pi/.ledrc')
# The base directory where all configs are stored. Each system should be its
# own folder; each game should be a text file in that folder whose name
# matches the game's name and has a "cfg" extension.
BASE_CONFIG_PATH = Pathname.new('/home/pi/leds')
class LEDState
def initialize(path)
@contents = path.is_a?(String) ? path : File.read(path).chomp
@button_map = {}
debug "config file contents: #{@contents}"
buttons = @contents.split(/,\s*/)
(1..16).each do |digit|
state = { value: 0, force: false }
if buttons.include?(digit.to_s)
state = { value: 1, force: false }
elsif buttons.include?("+#{digit}")
# "+x" syntax means we should force this button to be on.
state = { value: 1, force: true }
elsif buttons.include?("-#{digit}")
# "-x" syntax means we should force this button to be off.
state = { value: 0, force: true }
end
debug "State for button #{digit}:"
debug state
@button_map[digit] = state
end
self
end
def with_default(path)
debug "Combining with default config"
default = LEDState.new(path)
merge!(default)
self
end
def map
@button_map
end
# Converts the state to the format expected by the `pacdrive` utility.
def to_s
str = (1..16).map do |digit|
state = '0'
data = @button_map[digit]
if data && data.has_key?(:value)
state = data[:value] == 1 ? '1' : '0'
end
end
binary = str.join('').reverse
"0x%04x" % binary.to_i(2)
end
# Calls the external `pacdrive` app to set the LEDs to the represented
# state.
#
# Uses `exec`, so once this method is called, we implicitly exit.
def apply!
exec("/home/pi/bin/pacdrive", "-q", "-s", to_s)
end
protected
# For combining this state with another. The argument to this function is
# assumed to be a default, which means it will take precedence over this
# state when conflicts happen.
def merge!(default)
output = {}
default_map = default.map
@button_map.keys.each do |digit|
own = @button_map[digit]
dflt = default_map[digit]
result = nil
if !dflt[:force]
# Our version always wins.
result = own[:value]
else
# Default wants to force a value...
if !own[:force]
# ...and we don't, so use the default.
result = dflt[:value]
else
# ...and so do we, so we win.
result = own[:value]
end
end
output[digit] = { value: result }
end # each
# Replace the button map with the merged version.
@button_map = output
end # merge
end # LEDState
def debug(str)
return unless $options[:debug]
`echo "#{str}" >> #{$options[:debug_path]}`
end
if ARGV.size == 1
# We've been given a string like "1,2,3,7,8,9" (probably for debugging).
# Ignore all configs and just create and apply an LED state.
debug "Given input: #{ARGV[0]}"
LEDState.new(ARGV[0]).apply!
elsif ARGV.size == 2
# We've been given a system and a ROM name. Look up its config file and
# turn it into a binary string.
system, game = ARGV
debug "Setting LEDs for game #{game} on system #{system}..."
game_config_path = BASE_CONFIG_PATH.join(system, "#{game}.cfg")
if game_config_path.exist?
state = LEDState.new(game_config_path).with_default(DEFAULT_CONFIG_PATH)
else
# No specific LEDs for this game, so just apply the default.
state = LEDState.new(DEFAULT_CONFIG_PATH)
end
state.apply!
else
puts $usage
end
#!/usr/bin/bash
# ARGUMENTS, IN ORDER:
# 1. System (e.g., "arcade")
# 2. Emulator (e.g. "lr-fba-next")
# 3. Full path to game (e.g., /home/pi/RetroPie/roms/arcade/wjammers.zip)
if [ -z "$3" ]; then
exit 0
fi
system=$1
emulator=$2
# Gets the basename of the game (e.g., "wjammers")
game=$(basename $3)
game=${game%.*}
/home/pi/bin/led-end "$system" "$game" >/dev/null
#!/usr/bin/bash
# ARGUMENTS, IN ORDER:
# 1. System (e.g., "arcade")
# 2. Emulator (e.g. "lr-fba-next")
# 3. Full path to game (e.g., /home/pi/RetroPie/roms/arcade/wjammers.zip)
if [ -z "$3" ]; then
exit 0
fi
system=$1
emulator=$2
# Gets the basename of the game (e.g., "wjammers")
game=$(basename $3)
game=${game%.*}
# Turn on the relevant LEDs for this game.
/home/pi/bin/led-start "$system" "$game" >/dev/null
@jamesaar

This comment has been minimized.

Copy link

jamesaar commented Mar 3, 2017

Hi i have followed the readme up until the section below;

Now we're ready to install the pacdrive utility.

cd ~/src
wget "http://www.zumbrovalley.net/pacdrive/dnld/pacdrive_0_2.tar.gz"
tar xvzf pacdrive_0_2.tar.gz
cd pacdrive_0_2
make

however when i use the "make install'' command i get the error below.

install /usr/share/man/man5
install: missing destination file operand after ‘/usr/share/man/man5’
Try 'install --help' for more information.
Makefile:60: recipe for target 'man_5install' failed
make: *** [man_5install] Error 1

Do you have any idea what would be causing this?

Thanks

@savetheclocktower

This comment has been minimized.

Copy link
Owner Author

savetheclocktower commented Jun 7, 2017

Sorry, @jamesaar; didn’t see this until now. If you got all the way through make without any errors, the pacdrive binary should be sitting in the pacdrive_0_2 folder. You can manually copy it to /usr/bin or wherever else you want.

@nr002541

This comment has been minimized.

Copy link

nr002541 commented Jul 4, 2017

Hi

I have little experience with linux. I am having trouble with /home/pi/bin directory. In the file manger it shows up green and *bin. how to i create the led-start file here? i cant move to the directory because it says it does not exist and i cant create as it exists. i am using the standard retropie image.should these be going in the retropie folder instead of the /home/pi folder?

@savetheclocktower

This comment has been minimized.

Copy link
Owner Author

savetheclocktower commented Aug 25, 2017

@nr002541 Not sure what’s going on there, but you can put the binary in any folder in your path. Try /usr/local/bin, for instance.

@nr002541

This comment has been minimized.

Copy link

nr002541 commented Sep 20, 2017

I have just had another go. I think i have got all the files in the right place but nothing is working. What could i be doing wrong? If i call up the pacdrive program i can turn all leds on and off so this part must be working. Is there anything i can do to narrow down the problem?

@savetheclocktower

This comment has been minimized.

Copy link
Owner Author

savetheclocktower commented Sep 20, 2017

@nr002541 First of all, make sure you have Ruby installed — which ruby from the terminal should tell you.

Next, make sure that the scripts in question can be executed...

chmod +x /home/pi/bin/led-end
chmod +x /home/pi/bin/led-start

If it still doesn't work, try doing some logging within the scripts. At any point you can add a line like...

echo "got this far" >> ~/debug.txt

and it will append that text to debug.txt. That should help you narrow down where it's getting stuck.

@M4rc3lv

This comment has been minimized.

Copy link

M4rc3lv commented Nov 24, 2017

Had the same problem as jamesar. Had to change the Makefile in order to compile pacdrive. When running pacdrive it says "pacdrive: error while loading shared libraries: libhid.so.0: cannot open shared object file: No such file or directory". Makes sense because libhid.so.0 is nowhere. It looks that the makefile of libhid is also wrong. But building libhid gave no errors. I have given up :-(

@savetheclocktower

This comment has been minimized.

Copy link
Owner Author

savetheclocktower commented Nov 24, 2017

Oof! Too bad. I don't know what's changed — maybe the new version of Raspbian?

My original goal was to use hidapi (which is the de facto successor to libhid) and write something in Ruby via the hidapi bindings. But by my recollection (this was a year ago) the stuff that libhid was doing didn't have obvious parallels in hidapi, at least to a non-expert such as myself. Maybe I'll figure it out eventually.

@dweihe

This comment has been minimized.

Copy link

dweihe commented Feb 18, 2018

@M4rc3lv try running sudo ldconfig this should resolve the error

"pacdrive: error while loading shared libraries: libhid.so.0: cannot open shared object file: No such file or directory".

@ptahbe

This comment has been minimized.

Copy link

ptahbe commented Jun 24, 2018

I have the same issue
pacdrive: error while loading shared libraries: libhid.so.0: cannot open shared object file: No such file or directory

Did anyone find a solution?

@BigAl66

This comment has been minimized.

Copy link

BigAl66 commented Sep 3, 2018

Absolutely great. It works excelent. I made one change in led-start:

I defined a standard file that will be used whenever a configuration for a game does not exist:

# spcify a file that is used for a game's default configutation
BASE_CONFIG_FILE = "/home/pi/leds/default.cfg"

and at the end of led-start i create a file with the specified name automaticaly with the content of the "default.cfg":

After:
game_config_path = BASE_CONFIG_PATH.join(system, "#{game}.cfg")

The code end like this:

unless game_config_path.exist?
# create a config for the "new" game
system "cp " + BASE_CONFIG_FILE + " " + game_config_path.to_s
# give the user pi the chance to modify or delete the files
system "chown pi " + game_config_path.to_s
system "chgrp pi " + game_config_path.to_s
end
# now the state can be applied in any case...
state = LEDState.new(game_config_path).with_default(DEFAULT_CONFIG_PATH)
state.apply!
else
puts $usage
end

Now every time a game is started an there is no configuration a default one will be created automatically. I also share the folder 'leds' through the network. Now the files can easily be edited by notepad++ or any other editor...

Again: Thank you for this excelent word.

@Taranchul

This comment has been minimized.

Copy link

Taranchul commented Dec 14, 2018

I have found the solution to the error "libhid.so.0: cannot open shared object file: No such file or directory". The make install of libhid places all of its files in /usr/local/lib/, whereas on Retropie 4.4 (Raspbian Stretch) for the Raspberry Pi, the lib files are located in /usr/lib/arm-linux-gnueabihf/.

This command moves them to the correct location:
sudo mv /usr/local/lib/libhid.* /usr/lib/arm-linux-gnueabihf/

@savetheclocktower, maybe you could fix this in your modified version of libhid? That would be great!

@mdsavio

This comment has been minimized.

Copy link

mdsavio commented Feb 28, 2019

Hi all... I got this error when i install pacdrive_0_2

`pi@retropie:~/src/pacdrive_0_2 $ make
/usr/bin/gcc -Wall -c -DLINUX pac_prog.c
In file included from pac_prog.c:5:0:
pac_prog.h:30:17: fatal error: hid.h: No such file or directory

compilation terminated.
Makefile:40: recipe for target 'pac_prog.o' failed
make: *** [pac_prog.o] Error 1`

..... Maybe this... when install Libhib... another error...

In file included from linux.c:6:0:
../include/hid.h:5:17: fatal error: usb.h: No such file or directory
#include <usb.h>

Last Retropie 4.4 Raspberry Pi 3B

@compukit007

This comment has been minimized.

Copy link

compukit007 commented Oct 25, 2019

hi.
i cant even seens to get it working.
i get to
cd ~/src
wget "http://www.zumbrovalley.net/pacdrive/dnld/pacdrive_0_2.tar.gz"
tar xvzf pacdrive_0_2.tar.gz
cd pacdrive_0_2
make
and the make dos not work,
if i try sudo pacdrive -d is says pacdrive not found.
how can i fix it so it wil work.
and if i type led-end in a terminal i got the erro exec(%Q[/home/pi/bin/pacdrive -a -q])

thnx

@compukit007

This comment has been minimized.

Copy link

compukit007 commented Oct 25, 2019

Absolutely great. It works excelent. I made one change in led-start:

I defined a standard file that will be used whenever a configuration for a game does not exist:

# spcify a file that is used for a game's default configutation
BASE_CONFIG_FILE = "/home/pi/leds/default.cfg"

and at the end of led-start i create a file with the specified name automaticaly with the content of the "default.cfg":

After:
game_config_path = BASE_CONFIG_PATH.join(system, "#{game}.cfg")

The code end like this:

unless game_config_path.exist?
# create a config for the "new" game
system "cp " + BASE_CONFIG_FILE + " " + game_config_path.to_s
# give the user pi the chance to modify or delete the files
system "chown pi " + game_config_path.to_s
system "chgrp pi " + game_config_path.to_s
end
# now the state can be applied in any case...
state = LEDState.new(game_config_path).with_default(DEFAULT_CONFIG_PATH)
state.apply!
else
puts $usage
end

Now every time a game is started an there is no configuration a default one will be created automatically. I also share the folder 'leds' through the network. Now the files can easily be edited by notepad++ or any other editor...

Again: Thank you for this excelent word.

can you maby share that file ?
i dont now how to chance it so i got lots of errors
thnx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.