[SOLVED] Get arduino to communicate with mac (via applescript + SerialPortX)

The issue itself is in applescript yes, but it ties into interfacing with an arduino, so I just wondered if anyone else had the same issue and had found a fix.

Anyway, I managed to resolve this by not using SerialPortX, and instead parsing the arduino output directly through Terminal with applescript.

For anyone else reading through this, here is the code I use:

Arduino:

//Applescript will parse the entire history, so we need a way to inform it of new commands.
long CommandID = 100000;

void setup() {

  Serial.begin(9600);
  delay(2000); //Wait 2 seconds initially

}

void loop() {

  //For example, toggle pause every 2 seconds
  printCommand("play");
  delay(2000);
  printCommand("pause");
  delay(2000);

  //To add other commands, simply add code for the command in applescript:

}



void printCommand(String Command) {

  //Print the command ID
  Serial.print(CommandID);

  //Print the actual command
  Serial.println(Command);

  //Increase the command ID
  CommandID++;
}

Applescript:

set commandID to 100000

tell application "Terminal"
	
	-- Connect to arduino serial
	set resultTab to do script "screen /dev/cu.usbmodemYourArduinoHere 9600"
	activate
	
	-- Read output data forever
	repeat
		
		-- Polling rate (Increase this when you are not testing, as it wastes CPU otherwise)
		delay 0.1
		
		-- Next command ID to look for
		set commandIDString to (commandID as string)
		
		-- Read from the output
		tell front window to set t_Contents to (contents of selected tab)
		if t_Contents contains commandIDString then
			
			-- Split command from its ID
			set AppleScript's text item delimiters to commandIDString
			set Command to text item 2 of t_Contents
			
			
			
			
			-- Read the command, and do what we want
			-- Put your custom commands in here
			
			if Command contains "play" then
				tell application "iTunes" to play
			end if
			
			if Command contains "pause" then
				tell application "iTunes" to pause
			end if
			




			
			-- Look for next command
			set commandID to commandID + 1
		end if
	end repeat
end tell
  • It should be fairly obvious from here how to add custom commands. For the full documentation on itunes control, check here.
  • The YourArduinoHere part should the ID of your arduino. You can find this in the arduino UI if you go tools>Port.
  • Also, when you launch the applescript, it will hijack access to the arduino's serial output, so if you want to upload something new to the board or relaunch the applescript you will need to unplug it and replug it in.
  • There is probably a much faster way to do this, but I literally learned this yesterday, and hopefully this will point you in the right direction.