Blending Work and Play

Have you been wanting to dip your toes into the Bluetooth LE waters? Who can blame you? With the abundance of resources available in the market today in terms of hardware and software components, there’s never been a better time to jump into the world of physical computing. Throw in the power of Core Bluetooth on iOS and OS X, and you’ve got a recipe for a tasty bit of experimentation.

The Ingredients

1 RedBearLab Blend board (available here)

1 Breadboard

1 Piezo


1 R/C toy car platform or similar (Check a local thrift store or garage sales for a suitable choice.)

1 iPhone, iPod touch, or iPad (must support Bluetooth LE – see relevant Apple documentation)

1 Installation of Xcode

1 Installation of Arduino IDE with RedBearLab library and dependencies installed

Solder to taste

Hacked Tumbler

Building the Platform

You’ll need to build or hack a motorized chassis to use as the foundation of the project. One of my sons had previously purchased an R/C toy at a thrift store. He was pretty excited about the prospect of taking it apart and repurposing it for the Bluetooth experiment. This particular R/C car is a Thunder Tumbler which features two motors that are independently controlled, sort of like a zero-turn lawn mower. You can use pretty much any R/C car for your platform. If you choose one that is steered via a servo motor, the code in the sample project will need to be modified to interact with the servo.

We cut a small, thin piece of plywood and screwed it down to the top of the Tumbler. We cut slits and holes in the plywood so that we could place the board that holds the breadboard and Blend board on top of it without having to rigidly attach it to the car. Here’s a peak underneath the electronics.

Tumbler Platform

The board that the electronics are mounted on top of is from the Arduino Starter Kit. You certainly don’t need to use the same mounting board, but you’ll want something to hold things in place sufficiently. Note that this particular R/C car is capable of moving fairly quickly. With the loosely mounted electronics as shown here, you definitely want to avoid moving anywhere near maximum speed.

Wiring It Up

The control of the motors is achieved using an L293D H-bridge chip. This part also came with the Arduino Starter Kit, but they are readily available from a variety of sources. The bridge was wired up as shown below. The Leonardo shown in the sketch is a placeholder for the RedBearLab Blend board. The sketch also shows the connections made for the piezo and LED.

Tumbler Wiring

Not shown in the sketch are the connections to the Tumbler motors and the incoming power from the Tumbler. The motors are wired to the open pins shown on the L293D in the sketch. One motor is wired to the pins on one side of the chip and the other motor is wired to the pins on the opposite side. You may have to experiment a bit to get the connections right such that the motors rotate in the desired direction. For our Tumbler, we soldered a connector onto the motor leads so that we could quickly connect/disconnect the wires going to the breadboard. We also soldered pins onto the ends of the leads coming out of the Tumbler battery pack so that we could easily plug the power into the breadboard.

A Simple Command Language

With the platform built and the wiring in place, the next thing to consider was how the car would actually be controlled. The communication path would be Bluetooth LE, but I needed a way to represent commands that would make the car do what we wanted. What I ended up with was a simple packet structure that includes a single letter indicating the type of command and a payload of zero or more bytes. The commands implemented are as shown in the table below.

Command Payload Purpose
B 0 to turn off, 1 to turn on Control the LED
T 0 to turn off, 1 to turn on Control the piezo
R, L, F Two bytes as DS
D = 0 for reverse, 1 for forward
S = 0 to 255 for speed
R – Control the right motor
L – Control the left motor
F – Control both motors
S No payload All stop – turn off motors, silence the piezo, turn off the LED

The code running on the Blend board follows the usual pattern for an Arduino sketch. After running setup it spends the rest of its time in the loop. The main logic in loop is a switch statement that invokes the appropriate functions based on the commands received.

On the Phone

In Bluetooth LE, there are two roles: central and peripheral. The iPhone, or other iDevice of choice, plays the role of central whereas the RedBearLab Blend is the peripheral. The central initiates a connection with peripherals and then the two devices can exchange data with one another.

The data being exchanged here are the commands described above. On the iOS side, the commands are modeled via a Packet structure in the Swift source code. A Packet has a command member as well as an optional array of values that represent the payload.

When writing data to a peripheral, the Core Bluetooth API calls for supplying the data as an NSData object. Since the Packet structure consists of a UTF8Char command and the payload as an optional array of UInt8 values, we need a way to convert that to NSData. Here’s how it’s done.

var data: NSData {
    let data = NSMutableData(bytes: [command], length: MemoryLayout.size(ofValue: UTF8Char()))
    if (values != nil) {
        data.append(values!, length: values!.count * MemoryLayout.size(ofValue: UInt8()))
    return data

We might take a deeper dive into the code aspects of the project in a future post.

The user interface on the iOS device is minimalistic.

Blender UI

The two sliders are used to control the left and right motors. Slide up to go forward, down for reverse. The sliders snap back to center when you lift your finger to keep the Tumbler from going on a wild ride. The Horn and Light buttons are used to control the piezo and LED. The piezo will sound as long as a finger is held in place on the horn button. Likewise, the LED will be lit as long as a finger is held down on the light button. The Reset button is used to reestablish communication with the Blend board.

Big Finish

Here’s an epic video that shows the Tumbler in action. Absolute proof that learning useful skills can also be fun!

What do you think? Would you be interested in a deeper discussion of the code running on the Blend or on the iOS device? Let me know in the comments section.

All source code is available on GitHub. There’s also sample code that runs under OS X.


Swift Scripting (Part 4) – The Exciting Conclusion

Previously, we’ve covered the groundwork necessary to use Swift to control scriptable applications. (See parts one, two, and three.) Now we get to the payoff. We’ll have a look at a sample script that leverages the scripting interfaces of the Finder and the Image Events helper application.


To run the sample script on your own system, you’ll need to build and install the ScriptingUtilities, FinderScripting, and ImageEventsScripting frameworks. If you don’t want to create all of these from scratch, you can find ready-to-build Xcode projects in the SwiftScripting project on GitHub. Whichever path you choose to build the frameworks, be sure to install them in /Library/Frameworks.

Shrinking Images

The sample script operates on the current selection in the Finder. The result of running the script will be the creation of half-scale versions of any images that were selected. Any non-image in the Finder selection will be ignored. The “test” for images will solely rely on file extension, so we’re not talking about a fool-proof form of input verification.

Here’s the script

#!/usr/bin/swift -F /Library/Frameworks

// Image Events sample script.
// Operates on selected images in the Finder
// Outputs half-scale images in same folder as originals

import Foundation
import FinderScripting
import ImageEventsScripting
import ScriptingUtilities

let imageExtensions = ["png", "jpg", "jpeg", "tif", "tiff", "gif"]

let finder = application(name: "Finder") as! FinderApplication
let imageEvents = application(name: "Image Events") as! ImageEventsApplication

for item in (finder.selection!.get() as! NSArray) {
    if let file = item as? FinderFile {
        let fileExtension = file.nameExtension!.lowercaseString
        if imageExtensions.contains(fileExtension) {
            let fileURL = NSURL(string: file.URL!)
            let outputDirectory = fileURL!.URLByDeletingLastPathComponent!
            let outputFilename = "\((! as NSString).stringByDeletingPathExtension) (half-scale).\(fileExtension)"
            let outputURL = outputDirectory.URLByAppendingPathComponent(outputFilename)
            let image =!(fileURL!) as! ImageEventsImage
            image.scaleByFactor!(0.5, toSize: 0)
            image.closeSaving!(.Yes, savingIn: outputURL.path!)

The code is straight forward. On lines 14 and 15, the application function supplied by the ScriptingUtilities framework is used for convenience when assigning the finder and imageEvents constants. The work of the script occurs inside the for loop and we’re able to take full advantage of Foundation classes along side the scripting API of the Finder and Image Events. Go ahead and enter the above script into a text file and give it the name Scale Image by Half.swift. Remember to make the script executable using the chmod

chmod +x 'Scale Image by Half.swift'

Script Menu

While you could run the Scale Image by Half.swift script from anywhere on the system, it would be awkward to select some images in the Finder and then bring up a Terminal window to invoke the script. A better solution is to use the system-wide Script Menu to host your bits of automation. You enable the Script Menu via the Preferences of the Script Editor application.

Script Editor Preferences

With the Script Menu enabled, you now have a place to put all of your scripts and keep them organized by application. I like to configure the Script Menu such that the scripts for the frontmost application are displayed at the top of the menu. The screenshot below shows the Script Menu as it appears on my system with the Finder frontmost.

Script Menu with Finder Frontmost

If you select the Open Finder Scripts Folder option from the Script Menu, a Finder window will be opened at the appropriate location. This is where you want to put the Scale Image by Half.swift script. Once the script is placed in this location, it will be available as a menu option when the Finder is frontmost. To exercise the script, select one or more images in the Finder and then choose the Scale Image by Half.swift option from the Script Menu. If all goes well, you should see half-scale images appear alongside the originals.

Happy Scripting!