Tag Archives: Arduino

Control your Mac from an Arduino with JavaScript and NodeJS


Control your Mac from an Arduino with JavaScript and Node.js
// Web on Devices

Today, in this quick project we will hookup a simple push button to an Arduino UNO and trigger OS X, operating system level commands from Node.js and JavaScript. In this specific example we will put the computer in sleep and mute the system sound volume when the button is pressed. We will also look at a few other commands you can try by simply changing one line of code.

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.

button

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.

Displaying Images on a Dot Matrix LED Display with NodeJS


Displaying Images on a Dot Matrix LED Display with Node.js
By Patrick

sshot-10587.png
Dot matrix LED displays are fun. What developer wouldn’t love a blank canvas of lights to play with? I recently paired up a 32 x 16 Dot Matrix Display from Freetronics with Node.js and got it to display black and white PNG images. In this article, I’ll explain how it all works.

A dot matrix LED display (otherwise known just as a dot matrix display or DMD) is a display with a grid of LED lights that you can turn on and off to display text and shapes. Some of them have multiple colors, whilst others are just one single color. The one we’ll use in this demo has just one color, so we’re limited to black and white images. It is important to note – an LED display is quite different to an LCD display. LCDs use fancy light crystals and are used for displays on VCRs, clocks, calculators and so on. I wrote an article a few weeks ago on Displaying Web APIs on an Arduino LCD Using Node.js. Take a look at that if you’d like to compare the two.
This particular demo requires a Freetronics 32×16 Dot Matrix Display, as it relies on the Freetronics DMD library.

Demo code

If you’re keen to grab the code and give it a try yourself, you can find it here on GitHub.

The Freetronics DMD Library

Drawing lines, shapes and text onto our LED dot matrix display is all done via the Freetronics DMD Library. To use it, complete the following steps:

  1. Download the DMD library from their GitHub repository.
  2. Copy those files into your /Arduino/libraries/ folder under their own folder name. For me on my Mac, I placed it inside a folder at /Users/username/Documents/Arduino/libraries/DMD-master.
  3. Download the TimerOne library and place it into your /Arduino/libraries/ folder too. e.g. For Mac users, /Users/username/Documents/Arduino/libraries/TimerOne-r11.

Our Arduino Sketch

Most of the functionality for displaying elements on our DMD will happen within our Arduino sketch code. The sketch code will keep an eye out for messages over the serial port and change the display shown based upon those messages.
The sketch begins with our includes and constants. We include SoftwareSerial.h to allow us to access the serial port and define the width and height of our DMD (32×16 in our case). BUFLENGTH stores the number of lights we’ve got, as this is the max size of the message we want to send our Arduino. In our case, it is 32 multiplied by 16 which is 512.

#include 

Next, we have our includes specific to the Freetronics DMD. These should all be available from the files we copied into our Arduino libraries folder earlier.

#include 

Then, we have two constants DISPLAYS_ACROSS and DISPLAYS_DOWN which are used to define how many LED displays we have joined together. I’m going to assume you are in the same situation as me and just have one display, therefore both of these are equal to one. We then pass that into our DMD library, getting it running using DMD dmd().

#define DISPLAYS_ACROSS 1
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

The next bit of code is included in the DMD samples. This is the function we call to get the DMD library to refresh the display on a set interval. We define that interval a little bit further down.

void ScanDMD() {
dmd.scanDisplayBySPI();
}

We then define our last two variables. These two relate to receiving messages via the serial port. First, buf[BUFLENGTH] stores the buffer of serial port messages on which LEDs should be on and off. Second, bufCount will be used to store how many bytes within this buffer are left to read out.

char buf[BUFLENGTH];
int bufCount;

Our setup() function begins the whole process using our constants and defined libraries. It begins by listening on port 57600 for serial port messages.

void setup() {
Serial.begin(57600);

Then, we initialize a timer using the TimerOne library we included earlier. We tell it to countdown from four milliseconds. In Freetronics’ examples, they recommend not setting this to more than five milliseconds to avoid flicker on our display.

Timer1.initialize(4000);

We then set it to run the ScanDMD() function when our timer expires, which in turn refreshes the display.

Timer1.attachInterrupt(ScanDMD);

Finally, in our setup() function, we clear all pixels on the display by passing in true to the dmd.clearScreen() function. If you pass in false to this function, every pixel will turn on!

dmd.clearScreen(true);

In our Arduino’s loop() function, we keep an eye out for any messages on the serial port. We watch to see how many bytes are available for reading from the serial port. If there are bytes available, then we have a message streaming through and we run the serialParse() function.

void loop() {
if (Serial.available() > 0) {
serialParse();
}
}

Inside serialParse(), we set bufCount to -1 to reset the count value. Then, we read in 512 elements from that array (our BUFLENGTH) using Serial.readBytesUntil(). If there is a \n character, it will also stop reading the array. The main aim here is to keep the serial message within the length of our LED light grid.

void serialParse(void) {
bufCount = -1;
bufCount = Serial.readBytesUntil('\n', buf, BUFLENGTH);

If we do have a message in our buffer, then we send it through to parseBuffer() which will parse and display it onto our screen.

if (bufCount > 0) {
String message = String(buf);

parseBuffer(message);
}
}

Within the parseBuffer() function, we start by clearing the screen ready for us to it light up with a new drawing. Then we create an integer of i to keep track of which position in the array we are reading.
We then iterate through each character in our buffer, from left to right via x looping across until the SCREEN_WIDTH, and top to bottom via y looping down until the SCREEN_HEIGHT. This reads out our one dimensional array into the two dimensional display of our DMD. For each character, we check to see whether it is a '1'. If so, then we draw into that LED on the display at x and y. That will be used for the parts of our image that are black. If it is not '1', then we continue to the next position and so on. Eventually, drawing out our entire image.

void parseBuffer(char* buf) {
dmd.clearScreen(true);
int i = 0;
for (byte y = 0; y < SCREEN_HEIGHT; y++) {
for (byte x = 0; x < SCREEN_WIDTH; x++) {
if ((char)buf[i] == '1') {
dmd.drawFilledBox(x, y, x, y, GRAPHICS_NORMAL);
}
i++;
}
}
}

That covers how our Arduino works – if we run that code on our Arduino now with our LED attached, it displays nothing at all. To have anything display on our dot matrix display, we need our Node code to send it a message over the serial port.

Our Node Code

Our JavaScript begins by requiring two important npm modules. serialport is what will allow us to send messages via the serial port to our Arduino and png-js is what will read in our PNG images.

var SerialPort = require('serialport').SerialPort,
PNG = require('png-js'),

We then set up our serial port messaging. We set up a SerialPort object inside the variable serialPort, with settings for which port our Arduino is connected to and which baud rate we’ll be listening for serial port messages on.

serialPort = new SerialPort('/dev/tty.usbmodem1431', {
baudrate: 57600
}),

If you aren’t sure which port your Arduino is connected to (e.g. I have '/dev/tty.usbmodem1431'), connect it to your PC, open up the Arduino IDE, go to Tools > Port and see which is selected.
1434951555findingportname-1024x367.png
The baud rate can be personal preference, if you aren’t really concerned about which baud rate it is using, feel free to stick with the one we’ve already got in the example.
We then initialize a string variable called serialMessage which will store the full string of ones and zeros we’ll send through our serial port.

serialMessage = '';

Our serialPort object has an event listener of 'open' which it responds to when the serial port defined is open and ready to access from our JavaScript. When this is the case, we run console.log so we can be certain all is well with our serial port messaging.

serialPort.on('open', function() {
console.log('Serial port open');

Once we know our serial port is ready for messages, we run the PNG.decode() function to read in our PNG image file. In our demo, we’ve got a PNG image inside the same folder as our Node file called sitepointlogo-withsmile.png, so we pass in that file name. Then we have our callback function which provides us with the PNG file’s data via a data variable.

PNG.decode('sitepointlogo-withsmile.png', function(data) {
// We'll read in data here

The data returned from our PNG.decode() function will be an array of values from 0 to 255. They iterate through each pixel with a series of four items for each – a red, a green, a blue and an alpha value. We won’t be using the alpha value in our demo as we’re dealing just with black and white images but you theoretically could if you wanted to. A sample array looks like so:

[255,255,255,255,0,0,0,255]

The above array represents one white pixel with 255,255,255,255 and one black pixel with 0,0,0,255. This continues over and over for every pixel until we’ve represented the whole image.
Within our callback function, we reset serialMessage to be a blank string and then begin iterating through the data array in sets of four. We set a local variable of red, green and blue to match each pixel’s respective value.

serialMessage = '';
for (i = 0; i < data.length; i+=4) {
var red = data[i],
green = data[i+1],
blue = data[i+2],

In order to be able to deal with greyscale values that aren’t completely black or white, we’ve also got a luminance check. The function below determines how dark or light the pixel’s color is:

luminance = ((red * 299) + (green * 587) + (blue * 114)) / 1000;

If that value is greater than 150, then we’re assuming it’s a pretty light color and setting it to 0 (white). Otherwise, we set it to 1 and make it black. We append either value to the serialMessage string.

if (luminance > 150) {
serialMessage += '0';
} else {
serialMessage += '1';
}
}

Once we’ve gone through every pixel and allocated either a zero or a one to represent it, we send that message over the serial port using serialPort.write(). This whole process of reading in an image and iterating through actually seems to be faster than the time it takes for the display to be ready to receive it, so I’ve put it inside of a setTimeout to get it to wait two seconds before running.

setTimeout(function() {
serialPort.write(serialMessage);
}, 2000);

Running Our Demo

If you upload the sketch, connect the display to your Arduino and run the node server code via node serialDMD.js (remember to npm install everything first), you should see it light up with your PNG file like so:
1434950231ledinaction.jpg

Conclusion

There are plenty of ways you could expand on this. It is a Node server, so you could hook it up to an API and display images that pass through it. You could make it display a different image depending on time of day, the state of an internet connected device in your home, the weather or any number of other things!
If you expand out this idea into something really neat, let me know in the comments or get in touch with me on Twitter (@thatpatrickguy), I want to see!

Patrick’s latest venture is online at DevDiner.com, a site for developers looking to get involved in emerging tech. He is a SitePoint contributing editor focused on exploring and sharing the possibilities of new technology such as the Internet of Things, virtual/augmented reality and wearables. He is an instructor at SitePoint Premium and O’Reilly, a Meta Pioneer and freelance web developer who loves every opportunity to tinker with something new in a tech demo.

Remote Control Your Mac With NodeJS and Arduino


Remote Control Your Mac With Node.js and Arduino
By Patrick

sshot-10590.png
The combination of Arduinos and Node.js allows us to do a lot of unexpected things. In this article, I’ll show how you can create a remote control for your Mac via Arduinos, Node.js and AppleScript.If you are new to combining Arduinos and Node.js, I’ve previously covered turning on LED lights and displaying web API data on LCD text displays.
Our Arduino remote control will increase and decrease our Mac’s volume, tell our Mac to play an iTunes playlist of our choosing and set it to stop whatever is playing on iTunes (which is likely to be that playlist!).
Keep in mind, this demo provides access to commands directly on your Mac – there is the potential for this to be misused or harmful if you provide too much access! Keep it for personal use rather than big corporate projects.

Setting Up Our Arduino

Ensure that you’ve got the StandardFirmata sketch installed on your Arduino board itself, as we’ll be using the johnny-five library to send instructions to our Arduino. That will only work if you’ve got StandardFirmata on there first:
1432523568installingstandardfirmata.png
Our Arduino breadboard set up for this demo looks like so:
1432523768arduinomacremotecontrol.png

Our Server Code

Our Node.js server code is relatively short and sweet for this demo:

var five = require('johnny-five'),
board = new five.Board(),
exec = require('child_process').exec,
btn1, btn2, btn3, btn4, btn5,
currentVolLevels = {};
board.on('ready', function() {
console.log('Arduino board is ready!');
btn1 = new five.Button(7);
btn2 = new five.Button(6);
btn3 = new five.Button(5);
btn4 = new five.Button(4);
btn5 = new five.Button(3);
btn1.on('down', function(value) {
askiTunes('play playlist \"Top 25 Most Played\"');
});
btn2.on('down', function(value) {
askiTunes('stop');
});
btn3.on('down', function(value) {
setVolumeLevel(currentVolLevels['output volume'] + 5);
});
btn4.on('down', function(value) {
setVolumeLevel(currentVolLevels['output volume'] - 5);
});
btn5.on('down', function(value) {
toggleMute();
});
getVolumeLevels();
});
function getVolumeLevels() {
exec("osascript -e 'get volume settings'", function(err, stdout, stderr) {
if (!err) {
var levels = stdout.split(', ');
levels.forEach(function(val,ind) {
var vals = val.split(':');
if (vals[1].indexOf('true') > -1) currentVolLevels[vals[0]] = true;
else if (vals[1].indexOf('false') > -1) currentVolLevels[vals[0]] = false;
else currentVolLevels[vals[0]] = parseInt(vals[1]);
});
console.log(currentVolLevels);
}
});
}
function setVolumeLevel(level) {
console.log('Setting volume level to ' + level);
exec("osascript -e 'set volume output volume " + level + "'",
function() {
getVolumeLevels();
});
}
function toggleMute() {
var muteRequest = currentVolLevels['output muted'] ? 'without' : 'with';
console.log('Toggling mute to ' + muteRequest + ' muted');

exec("osascript -e 'set volume " + muteRequest + " output muted'", function() {
getVolumeLevels();
});
}
function askiTunes(event, callback) {
exec("osascript -e 'tell application \"iTunes\" to "+event+"'", function(err, stdout, stderr) {
console.log('iTunes was just asked to ' + event + '.');
});
}

That Code Explained

Now the all important part of the article – what all of that code means! Lets go over how everything fits together.
In order to interface with our Arduino board, we are using johnny-five. We start by setting up our johnny-five module and our Arduino board through that. Then we define variables to store our five buttons.

var five = require('johnny-five'),
board = new five.Board(),
btn1, btn2, btn3, btn4, btn5,

We also set up our exec() function which is what allows us to run AppleScript commands from Node.js.

exec = require('child_process').exec,

When johnny-five lets us know our board is ready to use, we run a quick console.log and define our five buttons and the Arduino pins they are connected to (7, 6, 5, 4 and 3).

board.on('ready', function() {
console.log('Arduino board is ready!');
btn1 = new five.Button(7);
btn2 = new five.Button(6);
btn3 = new five.Button(5);
btn4 = new five.Button(4);
btn5 = new five.Button(3);

On each button’s down event, we run a different function. On our first button, we run the askiTunes() function which sends iTunes a request. In our case, it is requesting our “Top 25 Most Played” playlist.

btn1.on('down', function(value) {
askiTunes('play playlist \"Top 25 Most Played\"');
});

The askiTunes() function executes our first bit of AppleScript using the exec() function. All of our AppleScript commands run within Node.js using the command osascript.
Our askiTunes() function runs the command osascript -e 'tell application \"iTunes\" to "+event+"'. This gives us a generic command telling iTunes to do something. We can adjust what that something is via the event variable.
When done, we run a console.log just so we know that the event has been recognised.

function askiTunes(event, callback) {
exec("osascript -e 'tell application \"iTunes\" to "+event+"'", function(err, stdout, stderr) {
console.log('iTunes was just asked to ' + event + '.');
});
}

Our second button runs the same askiTunes() function but we pass it the event of stop to stop anything that is currently playing.

btn2.on('down', function(value) {
askiTunes('stop');
});

If we had more buttons to play with, we could add buttons to pause and a generic play event that’ll resume what is currently in queue.
Our third and fourth buttons turn our Mac’s volume up and down via a function we’ll call setVolumeLevel().

btn3.on('down', function(value) {
setVolumeLevel(currentVolLevels['output volume'] + 5);
});
btn4.on('down', function(value) {
setVolumeLevel(currentVolLevels['output volume'] - 5);
});

setVolumeLevel() uses an object we define at the start of our code called currentVolLevels. This object stores the four different values which AppleScript returns from our Mac. A sample of this data looks like so:

{
'output volume': 5,
'input volume': 83,
'alert volume': 100,
'output muted': false
}

As you can see, we’ve got a value in that JSON object called 'output volume'. We add five to the volume level on our third button (increasing it) and reduce it by five on our fourth button (decreasing it), then we pass that value into the function to make the change happen.
Our setVolumeLevel() function uses the AppleScript command of set volume output volume to change our Mac’s volume to the level we’ve passed it. We also run a console log just so we can keep track of the volume level requests.

function setVolumeLevel(level) {
console.log('Setting volume level to ' + level);
exec("osascript -e 'set volume output volume " + level + "'", function() {
getVolumeLevels();
});
}

When our AppleScript code has been run, we call getVolumeLevels() which is our function that sets up all of our currentVolLevels values and keeps track of our Mac’s volume. I’ll explain it in detail after we’ve covered our final button.
That aforementioned final button runs the toggleMute() function that’ll mute and unmute our Mac.

btn5.on('down', function(value) {
toggleMute();
});

Our toggleMute() function looks at the currentVolLevels['output muted'] and uses either osascript -e 'set volume without output muted' to turn off muting or osascript -e 'set volume with output muted' to turn it on. If currentVolLevels['output muted'] is true, then we set the keyword to 'without' to take away muting. If it is false, we set the keyword to 'with' to turn on muting.

function toggleMute() {
var muteRequest = currentVolLevels['output muted'] ? 'without' : 'with';
console.log('Toggling mute to ' + muteRequest + ' muted');

exec("osascript -e 'set volume " + muteRequest + " output muted'", function() {
getVolumeLevels();
});
}

This AppleScript call also runs the getVolumeLevels() function once it is finished. In this function, we run osascript -e 'get volume settings' to retrieve the current volume of our Mac. It returns these values in the format:

"output volume:5, input volume:83, alert volume:100, output muted:false"

Within our getVolumeLevels() we take the value returned within the stdout variable and format it into a JSON object stored in currentVolLevels using code that looks like this:

function getVolumeLevels() {
exec("osascript -e 'get volume settings'", function(err, stdout, stderr) {
if (!err) {
var levels = stdout.split(', ');
levels.forEach(function(val,ind) {
var vals = val.split(':');
if (vals[1].indexOf('true') > -1) currentVolLevels[vals[0]] = true;
else if (vals[1].indexOf('false') > -1) currentVolLevels[vals[0]] = false;
else currentVolLevels[vals[0]] = parseInt(vals[1]);
});
console.log(currentVolLevels);
}
});
}

The JSON conversion is tailored specifically to the string we receive above. First, we split each key/value pair into an array called levels by splitting it between each comma to create an array like so:

['output volume:5', 'input volume:83', 'alert volume:100', 'output muted:false']

We then iterate through each string in the array, rearranging it neatly into our currentVolLevels JSON object. To do this, we split each key/value pair into an array called vals using the : character as our splitter. vals[0] will be each key such as output volume, whilst vals[1] contains the actual volume level values. We use vals[0] as our JSON object key, e.g currentVolLevels[vals[0]] = something.
There is one factor we need to keep in mind and account for in the volume levels that get returned. One of these values is a true/false value (our muted/unmuted status) whilst the rest are numbers. All of these are represented as strings and need to be converted. We’ll do this via a simple if statement that looks at the value of vals[1]. We check for the string of "true" and the string of "false". If we find either of these, we set the relevant value inside currentVolLevels to be the matching boolean. If it is neither of these, we parse the string into an integer that will represent a numeric volume level and store it inside currentVolLevels.
The end result looks like so:

{
'output volume': 5,
'input volume': 83,
'alert volume': 100,
'output muted': false
}

Our Package.json File

Our package.json file is rather simple in this case and mainly needs to ensure we’ve got the johnny-five and serialport npm modules installed.

{
"name": "nodemaccontroller",
"version": "1.0.0",
"description": "Code to control your Mac via Node",
"main": "index.js",
"dependencies": {
"johnny-five": "^0.8.76",
"serialport": "^1.7.1"
},
"author": "Patrick Catanzariti"
}

Our Remote Control In Action

Install all of the above dependencies using npm install, ensure your Arduino is connected and running the StandardFirmata sketch, then run node index.js. Upon running it, press a few buttons and you should be able to control your Mac! Whilst it’s running, it’ll look like this in the console:
1432533611ourremotecontrolrunning.pngOur Arduino Remote Control In Action

Other Possibilities

If you’re not a big music fan or you don’t use your Mac for your music, there are a bunch of other AppleScript shortcuts you could hook up your Node.js server to. Here are a few ideas.

Launch Applications

function openCalculator() {
exec("osascript -e 'tell application \"Calculator\" to launch'");
}

Open a New Finder Window

function openFinderWindow() {
exec("osascript -e 'tell app \"Finder\" to make new Finder window'");
}

Make Your Mac Speak!

function tellMacToSpeak() {
exec("osascript -e 'say \"I am completely operational, and all my circuits are functioning perfectly.\"'");
}

Conclusion

You’ve now got a neat way of making your own personal Mac peripheral! If you wanted to make it work as a portable device, you could set up either websockets, socket.io or a basic HTTP server, give your Arduino Wi-Fi or some other way of accessing your Node.js server remotely (or use something like a Particle Photon or Particle Electron microcontroller, and then make these exec() calls based upon remote commands (please be careful though, exec() can be misused!). There’s plenty of opportunity for some very fun projects here! As always, if you do make something neat, leave a note in the comments or get in touch with me on Twitter (@thatpatrickguy), I’d love to check it out!

Patrick’s latest venture is online at DevDiner.com, a site for developers looking to get involved in emerging tech. He is a SitePoint contributing editor focused on exploring and sharing the possibilities of new technology such as the Internet of Things, virtual/augmented reality and wearables. He is an instructor at SitePoint Premium and O’Reilly, a Meta Pioneer and freelance web developer who loves every opportunity to tinker with something new in a tech demo.

Displaying Web APIs on an Arduino LCD Using NodeJS


Displaying Web APIs on an Arduino LCD Using Node.js
// Kogonuso

LCDs. They’re fun. It’s one of the coolest ways to bring a voice to your Arduino as it speaks through glowing text. In this article we’re going to explore how to bring in data from a web API and display it on your Arduino’s LCD using Node.js.My favourite meetup of every month here in Sydney is the IoT Sydney meetup. It’s a great meetup (you should come along!). At the end of every meetup, there is a random prize draw for those who RSVPed. I thought it was about time that this was done in true IoT style, so I put together a quick Arduino LCD set up that pulls in Meetup.com event RSVP info and then randomly selects a lucky member. Thought it might be a nice surprise and way easier than drawing names out of a hat!
It also falls in neatly with the current series of Internet of Things articles I’m writing here at SitePoint. I’m exploring the many different IoT possibilities out there with various devices. Last week, I looked at using IoT data in the Unity game engine and before that, I looked at how to pull in data from the Jawbone Up.
Let’s get started!

Your Arduino Sketch

The sketch we’ll be using for this example looks like so:
1431043309lcdsketch.png
It is a slightly modified version of the one you’ll find in the Sparkfun Inventors Kit. There are other variations of LCD sketches you’ll find online that rearrange how things are connected up but will work the same way. You might just need to adjust which pins you define in the JavaScript below.

Our JavaScript Code

In our Node.js JavaScript file, we include the following:

var express = require('express'),
app = express(),
server = require('http').Server(app),
port = 5000,
five = require('johnny-five'),
request = require('request'),
_ = require('underscore'),
board = new five.Board(),
lcd;
board.on('ready', function() {
lcd = new five.LCD({
pins: [12, 11, 5, 4, 3, 2],
rows: 2,
cols: 16
});
this.repl.inject({
lcd: lcd
});
});
app.get('/chooseMember/:event_id', function(req, resp) {
request({
url: 'https://api.meetup.com/2/rsvps?key=474cc9332345ea7d7e135f50653c&event_id='+req.params.event_id,
json: true
}, function(error, response, body) {
var members = _.pluck(body.results, 'member'),
randomMember = members[_.random(members.length - 1)];

resp.json(randomMember);
console.log(randomMember.name);
lcd.clear().print(randomMember.name);
});
});
server.listen(port, function() {
console.log('Listening on ' + port);
});

Setting This Up Step By Step

If you’re pretty clued into Node.js, much of that code will already make sense to you. I’ll explain each bit just to ensure everyone is on the same page and provide guidance along the way on anything else we’ll need to set up.
To start with, we set up our express server variables in preparation to run a localhost server on port 5000:

var express = require('express'),
app = express(),
server = require('http').Server(app),
port = 5000,

We’ve then got a rather important thing to include, johnny-five. This is the npm library which gives us access to the functions we’ll need to control our Arduino via Node.js.

five = require('johnny-five'),

After that, we’re including the request module. We’ll be using this to make http requests from our Node.js server to the Meetup API.

request = require('request'),

To keep things very clean and simple, we’ll be using underscore to go through the arrays of data.

_ = require('underscore'),

The final two variables are the board and lcd variables that we’ll use to store the Arduino objects that johnny-five creates.

board = new five.Board(),
lcd;

We begin by waiting for our Arduino board to be ready to access, johnny-five sends a “ready” event when our board is ready to go.

board.on('ready', function() {

Once our board is ready to go, we let johnny-five know what sort of LCD we’ve got connected. We define the pins from top to bottom in an array:
1431043415lcdsketchwithpins.png
We also define how many rows and columns our LCD has. In my case it is a 2×16 LCD. All of this looks like so:

lcd = new five.LCD({
pins: [12, 11, 5, 4, 3, 2],
rows: 2,
cols: 16
});

Then we’ve got code which is optional (but handy to include) that will allow us to access the LCD functions from our command line as it is running (I’ll show this in action later in the article):

this.repl.inject({
lcd: lcd
});

Then, we have our one and only GET request that we’ve set up. In this request, we are expecting an event ID within the URL. For example: http://localhost:5000/chooseMember/221960710. The event ID is the one that you’ll find in the address bar when you visit the event’s page:
1431043678findingeventid.png
Our GET request looking for this ID looks like so:

app.get('/chooseMember/:event_id', function(req, resp) {

Then we get to the complex bit of the code! Our actual HTTP request to the Meetup API. We access this via the request function. We pass in two things here, our http options for the request and our callback function.
The options for our http call contain our url and a boolean to let the request know we’re expecting a JSON object back. This looks like so:

request({
url: 'https://api.meetup.com/2/rsvps?key=089cc9874628ealkjh27dkb50653s&event_id='+req.params.event_id,
json: true
}

Keen observers will have noticed we pass in our event ID from the URL string into the request URL using req.params.event_id. However there’s another string of characters in there which I haven’t explained. In order to access the Meetup API you’ll need an API key. You can find one of these at https://secure.meetup.com/meetup_api/key/:
1431043737gettingapikey.png
Finally, we’ve got our callback function which uses the returned JSON data. I’ve kept it simple and without error handling, however if this is a serious production level creation – add a check for the error variable.
The JSON output that the callback will return in our body variable looks like so:

{
"venue": {
"country": "au",
"city": "Sydney",
...
},
"created": 1428838649000,
"response": "yes",
"member_photo": {
"highres_link": "http://photos1.meetupstatic.com/photos/member/2/c/6/c/highres_161711372.jpeg",
"photo_id": 161711372,
...
},
"guests": 0,
"member": {
"member_id": 098361926,
"name": "Patrick Catanzariti"
},
...

We filter out a lot of that by using the _.pluck() function in underscore. This will help us focus on the important bit of our API – the members who RSVPed. The _.pluck() function goes through the results array and takes only the member info from each one.

function(error, response, body) {
var members = _.pluck(body.results, 'member'),

Then, we use the _.members() underscore function to randomly select a member from the resulting array.

randomMember = members[_.random(members.length - 1)];

We return that data through our express server as a JSON response to the GET request and log the name in our console so we can see who was chosen:

resp.json(randomMember);
console.log(randomMember.name);

Then we use the lcd johnny-five object we set up earlier to print out the name of the member onto our LCD. We start by using lcd.clear() to clear the LCD of anything currently on it and then use lcd.print() to print out the name characters.

lcd.clear().print(randomMember.name);
});

You’ll notice when you run this that some long names will get cut off, rather than wrap to the other line. If you’d like to wrap things onto a second line, try separating your randomMember.name into two 16 character strings, print the first string and then use lcd.cursor(1, 0); to move to the second line before printing the second one. In my case, it wasn’t needed as all we really need is to be able to tell whose name was drawn – a few missing characters usually won’t cause issues here.

Getting That Running On Your Arduino

We’ve got our Node.js code ready. Now, connect up your Arduino and make sure you’ve got the StandardFirmata sketch uploaded on it:
1431043878standardfirmatasketch.png
We’ll also need to make sure we’ve got all the dependencies sorted out. My package.json file looks like so:

{
"name": "MeetupRSVPSelector",
"version": "1.0.0",
"description": "Connecting the Meetup API to our Arduino LCD",
"main": "rsvp-selector.js",
"author": "Patrick Catanzariti",
"dependencies": {
"express": "^4.12.3",
"johnny-five": "^0.8.34",
"request": "^2.55.0",
"underscore": "^1.8.3"
}
}

Feel free to adapt that to your own project, the main thing you’ll want is those dependencies.
Then once you’ve got a package.json file sorted out, open up your console and go to the location of your code. Run this wonderful command:

npm install

Followed by this one:

node rsvp-selector.js

With that running, you should now be able to go to http://localhost:5000/chooseMember/221960710 (substitute your own event ID of course) and you’ll have a random rsvp appear as a result:
1431043936browserresponse.png
If you run it again, a new rsvp will appear. If all is going well, these names should be appearing on your Arduino’s LCD!
1431044034nameresponse.jpg

That Repl Thing We Mentioned

We included a bit of code that said this.repl.inject in our Node.js server earlier. What this does is allow you to run commands from within the terminal whilst your Node.js server is running to set what is being displayed on the LCD screen:
1431044066lcdclear.png
If we type in an lcd.print() we can get some magic happening:
1431044077lcdprint.png
Well… our message almost fit at least!
1431044305sitepointsayshi.jpg

Conclusion

We’ve successfully got a randomly selected member of the event group appearing on our LCD! This same idea could be applied to any number of other APIs out there, just adjust the request call and how you handle the data. Leave spooky messages on an LCD for housemates, keep tabs on the latest NBA playoffs scores or whatever else takes your fancy!
Make something fun based upon this code? Leave a note in the comments and share it around, I’d love to see it!

Patrick’s latest venture is online at DevDiner.com, a site for developers looking to get involved in emerging tech. He is a SitePoint contributing editor focused on exploring and sharing the possibilities of new technology such as the Internet of Things, virtual/augmented reality and wearables. He is an instructor at SitePoint Premium and O’Reilly, a Meta Pioneer and freelance web developer who loves every opportunity to tinker with something new in a tech demo.

Video NodeBots: JavaScript Powered Robots with Johnny-Five


here no denying that JavaScript is everywhere! But did you know that you could also use it to interact with a range of Sensors (i.e. distance, pressure and heat) and control Actuators (i.e. servos and LED’s)? Attend this lightning talk to find out more about the NodeBots revolution!

In 10 fast paced minutes you’ll learn about how you can get started with JavaScript powered Robots using an Arduino UNO and the Johnny-Five framework. If you are interested in picking up some JavaScript, Node.js, Arduino, Robotics or Electronics skills then this is the lightning talk for you!

There’ll also be drones!

JavaScript Powered Arduino with Johnny-Five


via JavaScript Powered Arduino with Johnny-Five – Safari Blog.

Atwood’s Law: Any application that can be written in JavaScript, will eventually be written in JavaScript.
Jeff Atwood, July 17, 2007

Other than the near omniscience of Edsger Dijkstra, I don’t think any prediction of the future of software development has been so dead-on as Atwood’s Law. JavaScript is everywhere: running applications in browsers, running the servers that feed HTML to the browser, and running database engines, to name a few. It should be no surprise, then, that JavaScript can also be used to control off-the-shelf hardware, circuits and other electronics like the Arduino platform. Through the use of frameworks like Rick Waldron’s Johnny-Five for NodeJS, and the “StandardFirmata” software package for Arduino, you can write JavaScript on your computer and use it to control and manipulate nearly any aspect of an Arduino-based hardware setup.

But before you take over the world with your JavaScript powered robots, you’ll need to get a few of the basics out of the way. You’ll need to know how to get an Arduino to communicate with your JavaScript program. You’ll need to know how to build a circuit that works properly. And you’ll need to know how to manipulate that circuit, through the use of Arduino, with your JavaScript code. And before you do any of that, you’ll need a few hardware parts to work with.

Cylon NodeJS (Universal Windows) Sample


via Windows IoT – NodejsWUCylon.

In this sample, you will use Cylon running on a Raspberry Pi 2 to control a servo connected to an Arduino (with Firmata installed).