29 Dec 2015, 10:06

Raspberry Pi GPIO Projects in Swift

Warning - this is a technical post

It’s been a super good break for me here in Salt Lake.

I got a Raspberry Pi for Christmas, and I’ve been constantly working on it. Since my other recent projects are in Swift, I felt like using it for a bigger GPIO project: a morse decoder/encoder.

Installing Swift on the RPi

This was, to be honest, the most difficult part of the project. At first when I looked into this, it wasn’t possible, because the Pi has an ARM processor instead of x86. But then I this tweet popped up on my timeline, and I got back to it. The next snag was related to Raspbian. I couldn’t get the package to work on the standard Raspberry Pi linux flavor, so I started over and installed a fresh Ubuntu image. Then the installation went smoothly.

Wrapping wiringPi in Swift

The Raspberry Pi has 40 GPIO pins that can be used for interacting with the outside world - people plug in things like temperature sensors or servo motors. My brother gave me the idea of writing a morse code system with an LED and a push-button. There’s a Python library for interacting with these pins programmatically, but writing Python doesn’t feel like gaining experience anymore. wiringPi is a C library with functions for getting input and output from the pins, which is perfect for wrapping in Swift. Figuring out which .o files I needed to link against was just a matter of adding until I didn’t get anymore compiler errors, and I ended up with this simple Makefile.

Writing the code

The encoder is easy: Just write a dictionary literal of morse code characters, run the input through that, and flash the LED for the right lengths of time. The decoder is tricky, and I still haven’t finished it because of some problems with my pushbutton. I’ve settled on the basic design of writing two functions that get the length of a press or a release, and passing control back and forth from them in a main update loop until a letter or word is finished. My buttons are a little unreliable right now, so I can’t really test this part until I do a little bit more hardware work to get the input right. I’m pretty sure the code will work as soon as the button does, so for now, I’m putting the project up on Github!