Thursday, March 3, 2011

Using the OS X terminal to control the Arduino

Sometimes it would be good to be able to control the Arduino live from a computer using the keyboard. Unfortunately AppleScript doesn't provide a way to detect keyboard strokes. But you can use the Terminal app of OS X instead. OS X comes with a UNIX screen command that allows to communicate with the serial port.

My sample Arduino sketch below starts or stops blinking of the internal LED on the Arduino board depending on two keystrokes. Of course those keystrokes could also trigger more useful camera control tasks.

Start OS X
Find serial device name: ls /dev/tty.*
Open terminal session: screen [serial device name] 9600 
Close session: ctrl-A ctrl-\
\ = shift-alt-7 on some keyboards

#define LED 13 
byte inbyte = 0;
boolean active = false;

void setup() {
  Serial.begin(9600); //open the serial port
  pinMode(LED, OUTPUT); 
  Serial.println("Type b to start and s to stop blinking of the Arduino LED");
  Serial.print(">"); //simulate prompt

void loop() {
  inbyte =; //Read one byte (one character) from serial port.
  if (inbyte == 'b') { 
    active = true; 
    Serial.println("b"); //echo the command
  if (inbyte == 's') { 
    active = false; 
    Serial.println("s"); //echo the command
  if (active) {
     digitalWrite(LED, HIGH);
     digitalWrite(LED, LOW);
   } else {
     digitalWrite(LED, LOW);

Download the sketch then start the OS X
Find the serial device name of the Arduino with ls /dev/tty.*
Open a terminal session using screen [serial device name] 9600
e.g.: screen /dev/tty.usbserial-A6004byf 9600

Close the screen session and free the serial connection for use with the Arduino development envirement by typing
ctrl-A followed by ctrl-\ followed by y
\ = shift-alt-7 on some keyboards

Tired of typing? Save the AppleScript below as an app to get a double-clickable application to launch a serial Terminal session.

tell application "Terminal"
 do script with command "screen /dev/tty.usbserial-A6004byf 9600"
 set number of rows of window 1 to 20
 set number of columns of window 1 to 50
 set background color of window 1 to "black"
 set normal text color of window 1 to "green"
 set custom title of window 1 to "Let's talk to the Arduino"
end tell