This project really is a simple one. The Arduino code will be 7 lines and the Node.js application is 14 lines so I encourage you to try it! We will first check the button state with the Arduino, then send a message through the USB port to the Node.js application where we simply run terminal commands to perform certain tasks.
If you would like to get started from the very basics of Arduino and Node.js, download my Free ebook which will teach you all the basics in a few hours.
For the button I used a breakout board. This module has three pins: S, V and G. V is what you connect to the 5V pin on the Arduino and G to the GND pin. After this the button is powered up. The last step is to connect the third pin, S (Signal) to one of the input pins of the Arduino. The button connects the supplied 5V voltage from the V pin straight to the S pin but breaks the circuit when you press the button. This voltage change is what you’re Arduino input pin will detect. I randomly picked number 6 for this circuit.
After this I opened up the Arduino IDE and wrote the sketch that first checks whether the button is pressed then sends a message through the USB port. This serial message is what we will later pick up and read from Node.js using the serial port library.
This will result in the “Clicked” serial port message sent through the USB when the button is clicked.
Node.js server part
In our Node.js application we first include the Serialport library then save the library instance into another variable. In the third line we load the Shell JS library which will let us run OS X Terminal commands within the Node.js application.
Next, we create an instance of our USB port by passing in the name of the port, then a settings object that specifies that we will interpret a message when a new line character is received.
The USB port instance has an on data event listener which exposes a data variable containing our message:
The problem with this piece of code is that when we press the button the Arduino constantly keeps streaming the “Clicked” message one by one until we release the button. This means that whatever we put inside condition will be executed multiple times. To prevent this from happening we only interpret the first message as a click, then disable the functionality for the next five seconds:
After the button logic is sorted let’s look at all the things we can do with OS X from here:
This is just the beginning and you can obviously add most Terminal commands in here. You could automate a GIT command or a Grunt or Gulp task you often have to use.
What would you use this script for?