Tweet Monkey!

This is a very, very simple maker project. It’s clean. It’s easy. It’s quick. I’m hoping the process and architecture inspire you to make something of your own, and I hope the world of possibilities in this space start opening up for you as they are for me (as evidenced by my fantastically long project idea list).

Let’s get started!

Here’s the Big Idea

We’re going to use a microprocessor with wifi to monitor Twitter’s streaming API for tweets with a certain hash tag and then when one lands, we’ll activate a dancing, squawking, symbol clanging monkey for 2 seconds. Two seconds should be enough to see him go through his entertaining gyrations. Each subsequent tweet will again set our monkey into motion and hilarity will ensue.

Perhaps you’ve seen projects done with low-level boards like the Arduino, one of Particle‘s boards, or the tiny ESP8266. I’m a fan of those boards, but for this project, we’re calling into Twitter’s streaming API. On the surface, that seems like a simple thing, but under the hood there’s a lot that needs to happen. Regardless of what sort of client you’re using to connect to the popular Twitter service, you have to authenticate. That means that you have to use Oauth. And that means that you have to do a bunch of work in your HTTP headers. But I don’t want to do that work. I want this to be easy. Node.js makes it easy, so we’re going to use a board that supports Node.js.

For this project, we’re going to use an Intel Edison running Node.js. Node.js runs JavaScript, which is a high-level scripting language that, despite its origins in front-end development, feels very much at home on the server, in apps, or on devices. The syntax of JavaScript is nice and all, but the real value of running Node.js for this project is the fact that we can use a Node module that has already been written to handle all of the Twitter complexity. We’ll end up with a very short code block that does just what we want.

You can use whatever you like for editing the text files, but I’ll be using the free Visual Studio Code.

My original Tweet Monkey product used the Edison on an Arduino breakout board with a USB battery pack and a big relay. The entire solution was pretty huge.

I’ve modified the steps below to make it more accessible. I include the complete list of materials you’ll need to purchase, and it’s cheaper than if you were to purchase the Arduino dev board and the Seeed Grove Kit that included the relay. Furthermore, because the Edison is no longer required to live on the Arduino breakout board, it takes advantage of one of Edison’s biggest features - it’s small size.

Here’s what the entire project is going to look like from a hardware standpoint, just so you know…

Here’s what you’ll need

**Item** **Price** **Link**
Monkey $12 [Amazon](http://www.amazon.com/dp/B0000V4H4O/ref=sr_ph_1?m=A2NL9UUKFTRQH&ie=UTF8&qid=1438886567&sr=sr-1&keywords=magic+monkey)
Intel Edison $50 [Sparkfun](https://www.sparkfun.com/products/13024)
Edison battery module $25 [Sparkfun](https://www.sparkfun.com/products/13037)
Edison GPIO module $15 [Sparkfun](https://www.sparkfun.com/products/13038)
MOSFET $0.88 [Digikey](http://www.digikey.com/product-detail/en/STP16NF06/497-2766-5-ND/603791)
1/4W Resistor Kit $15 [Digikey](http://www.digikey.com/product-detail/en/RS225/RS225-ND/7110)
Drill and 1/6" drill bit
2' 22-gauge wire
Short M-F jumper wires $3 [Digikey](http://www.digikey.com/product-detail/en/MIKROE-512/1471-1231-ND/4495595)
20-pin Pin Header Strips $6 [Digikey](http://www.digikey.com/product-detail/en/M20-9992046/952-1902-ND/3727869)
Micro-USB cable and power source
2 AA batteries

Step 1. Buy the monkey

I found mine at a local novelty shop here in Seattle called Archie McPhee, but it’s the same as this one on Amazon.

Step 2. Mod the monkey

This monkey comes out of the box ready to entertain children with a simple on/off switch on his butt. Well, we’re not children, and that’s not going to work for us. We’re using our monkey for serious business - serious monkey business.

So the first thing we need to do is inspect our monkey’s downstairs and see how this on/off contraption works.

Here’s what I see…

Every project is different. Here’s what I’m looking for.

We’re dealing with a complete circuit here. There are two AA (1.5V) batteries and they’re hooked up in serial, so that means that this monkey runs on 3V and some unknown amount of current will be drawn.

You don’t often know how much current any given load is going to require. You could put meters in the circuit and measure, but the better thing to do is to simply leave a circuit as is with it’s own power source and everything. The other option would be to attempt to merge the circuits of our load (the monkey) and our microprocessor, but that’s where you have to be careful. Microprocessors tend to cost real dollars. Ironically, the Edison I’m going to introduce soon - an amazing work of engineering art - is only 3x the price of this silly mechanical monkey! The inner workings of computers are child’s play compared to the inner workings of our global economy. But I digress. My point was that you don’t want to toast your Edison. So we want to control the monkey by simply doing the equivalent of turning the switch on an off.

What we discover in this monkey’s butt is that the switch on the outside of the trapdoor is simply connecting or disconnecting the ends of the batteries and completing or breaking the circuit. So let’s do the same. Let’s simply tap into the two contacts with some wires, run them out, and use software to virtually touch the ends of the wire together.

We need to run wires outside all clean like, so let’s drill some very small holes through the trap door and run wires through. Then we’ll set up a soldering station and solder the wires directly to the contacts.

Now we can close the door and we’ve got two wires that when touched together complete the circuit and set the monkey in motion. Conveniently, we have not disabled our on/off switch, so if we wish to use it to turn the monkey on, we can still do that.

And just like that, we’re done with surgery. Your monkey should recover nicely.

Step 3. Add a component to complete the circuit

The question now is how to programmatically connect these two wires to complete the circuit. There are a number of options, and I’ll enumerate them.

Option 1. We could hook the positive wire to a pin on our microprocessor and the negative wire to the ground of our circuit. There are some considerations with this approach, and in our case here, there are some real problems. Different devices have different voltage levels for their logic. We’re going to be using an Edison with the Arduino dev board installed. The logic on the Arduino board are 5V, and that’s actually because the dev board is level shifting them up for us, because the logic levels on the Edison itself are only 1.8V. So as long as we’re using the dev board, if we attempted to hook our logic directly up to the monkey’s circuit, we’d be combining the power source of our microprocessor with our monkey’s own AA power source. That’s not a good idea.

Option 2. A mechanical relay is a nifty device that has 2 circuits. On one circuit, it let’s you give it a logical 0V or 5V level. If you give it 0V, then the second circuit will be open. If you give it 5V, then it will mechanically connect (as in, internally touch two pins together with metal) the other circuit so that electricity will flow. You will actually hear a click when a relay is activated. It is not, obviously, a power source. It simply let’s you decide whether to open or close a circuit so that whatever power source it has will or will not flow. This is the option we’re going to use for this project simply because I have one readily available.

Option 3. A solid state relay works exactly like a mechanical relay except: a) it tends to handle smaller amperage values on the secondary circuit, and b) it is perfectly silent. I have some of these on order, but they’re not in yet. A solid state relay is usually created with an optoisolator that uses a small light source (an LED) and a small light pickup (a phototransistor) internally. This decouples the circuits and allows the whole thing to operate silently.

As I mentioned, I have a mechanical relay on hand, so I’ll use that. It’s capable of handling 10A which is far more than we’ll need it for, but it will work. By the way, I believe this relay takes 5V to trigger, so we wouldn’t be able to use it with the Edison alone. We must have the Arduino dev board. The wires coming out of the monkey’s hind end are attached to the relay board in the green connector with flat screws on top. Here’s the relay…

I got this relay from a Grove Seeed Kit (intentionally misspelled). The nice thing about this kit is that it makes all of the components easy to hook up. The white 4-pin connector you see on the component fits a bundle of wires that also comes with the kit and again into an Arduino-compatible shield, which you’ll see next.

Step 4. Adding the microprocessor

Next, I plugged my relay into my base shield. The base shield is on my Arduino dev board, and the Edison is mounted to the same. The Edison needs power, and that’s easily provided with a simple USB battery pack.

At this point, we have all of our hardware hooked up and are ready to implement some logic.

Step 5. Writing the software

We’re going to be writing JavaScript in a Node.js project on this Intel Edison to get this monkey grooving. If you are pulling an Edison out of the box and need help setting it up, have a look at codefoster.com/edison-setup. For the rest of this article, you’ll need your device to be all configured and on the same wifi network as your host PC (the one you’re using Visual Studio on) and you’ll need to know the IP address and the login password.

If you haven’t already, go to visualstudio.com and download and install Visual Studio Community 2015. Then go to http://nodejstools.codeplex.com and download and install the Node.js Tools for Visual Studio.

Now clone https://github.com/codefoster/tweetmonkey.git and open the tweetmonkey.njsproj file in Visual Studio. Let me point out a few things about this project.

  • There’s a config.js file that you need to fill in with your particulars.
  • Go to apps.twitter.com and create a new app to get the Twitter API keys and secrets.
  • There’s a gulpfile.js that has a deployment project. The IP address and password you enter into the config.js will determine where this project gets deployed.
  • There’s a { track: '#cfmonkey' } in the app.js that you need to change the value of. This is what the search is going to look for. This is not looking for tweets from a user actually, but rather looking for tweets with certain text in the body. I will try to update the GitHub repo with comments for how to search for tweets to a certain user.
  • The code in the app.js is hooking into Twitter’s “streaming API”. This means that you don’t have to poll the service every second to see if any relevant tweets have landed yet. Rather, Twitter will look for them and when one does land, it will call the your code’s function. That’s a thing of beauty!

Step 6. Running the app

Ideally, I’d have another gulp task for executing the Node.js project on the device, but I haven’t quite figured that out yet, so I just SSH to the device and run it.

I’ll assume you’re all set up for using SSH since you’ve supposedly gone through my /edison-setup article already.

To SSH, use…

ssh root@192.168.1.13 (or whatever your IP address happens to be)

Once on the device, cd to the project directory (it should be in the default location depicted by the ~ in the prompt - this is likely /home/root) and then use…

node app.js

Step 7. Testing it

Testing it is easy. Just send a tweet with the chosen text and watch your monkey dance!

Something more compact perhaps?

The final solution is by no means compact. You have a big, green board hanging out of monkey’s bum by wires and a USB batter pack to boot. So how might we make this solution more compact? I’ll tell you. Take a look at the Edison on its Arduino dev board. Most of that is dev board, right? The Edison itself is very small. So if we could get rid of the dev board, that would be a huge step. Of course, then we need to power the thing and a way to access the logical pin that controls the relay. So, we could simply head back to SparkFun.com and order a couple of Edison modules. These things are great in my opinion. For this solution, we could use the Edison itself, a GPIO breakout module, and a battery module. Then we’d have to replace our relay with something smaller - no problem since the relay I used was way overkill. Then we’d probably want to find a creative way to conceal the whole thing. We could give our monkey a backpack, for instance. In some cases, you can power your Edison from the same source as your project, but in this case, the monkey is carrying 3V and our Edison needs 3.7V at a minimum, so I wouldn’t feel good about that.

Conclusion

So there you have it - a simple, end-to-end tweet monkey! Just what everyone needs.

I hope you had fun with the monkey specifically, but more importantly, I hope you’re just a little bit more comfortable hooking into an existing electronic circuit and using logic from a program you wrote to manipulate it. When you get the concepts behind the procedures, you really start to see the possibilities, and that is the heart of the maker movement.

I recorded a session about Tweet Monkey’s older brother - Command Monkey as a CodeChat episode with my colleague Jason Short (@infinitecodex). Here you go…

Using Visual Studio to Write Node for Devices

In previous blog posts, I explained how to setup your Intel Edison and how to start writing code for it. And in case you got here directly, I created a full index of my Edison posts to help you find what you need.

In this post, we’ll take a look at writing code for it using Visual Studio. Visual Studio, once you add the free Node.js Tools for Visual Studio plugin, happens to be pretty great at working with Node.js projects. It runs node behind the scenes, so it offer the following…

  • Editing
  • Intellisense
  • Profiling
  • npm
  • TypeScript
  • Debugging (local, remote, and Azure!)

That’s an impressive list, and we’ll take a look at a few of these features in this post.

Closer to the end of this post, I’ll tell you about my edref project. “edref” stands for Edison Reference project and is intended to get you started quickly with an Intel Edison project in Visual Studio. If you want to skip all the rhetoric and just download the reference project, I’ll understand.

Visual Studio

In case you missed the announcement in November, Visual Studio Community edition is now free. That’s huge. The Community edition is essentially the existing Professional edition, and facilitates a huge array of development scenarios. VS is intuitive, intelligent, and has a lot of Microsoft and community support behind it.

Installing Visual Studio Community 2013

To download Visual Studio, start at visualstudio.com, but know that visualstudio.com sort of has two meanings right now. Visual Studio is the IDE, but it’s also the ALM tools for taking any size projects from conception to completion with any size group of developers. So click the download button under Visual Studio the IDE and (at least at the time of this writing) you’ll get a direct link to the Visual Studio Community 2013 package.

Installation is pretty straight-forward, and I won’t include a screenshot series, but one decision you will have to make is which features of the product to install. Do you want to play with Lightswitch? Windows Phone? Just check the boxes.

The next version of Visual Studio is Visual Studio 2015 and there’s pretty good support for it already (including a working version of the Node.js Tools), so if you want to be a trailblazer at work, go for it.

The Node.js Tools for Visual Studio

Installing the Tools

The Node.js Tools are found at nodejstools.codeplex.com. Go there and click the gigantic, unmistakable DOWNLOAD button. Again, the download is assumedly self-explanatory.

Creating a New Project

Creating a project using Node.js in Visual Studio begins like any other project type - with the File | New Project dialog…

There are a number of projects to choose from. For what we’re dealing with - writing Node.js for devices - the Blank Node.js Console Application will suffice. The rest are web applications for creating node apps on the server.

As per usual, give your project a name and location and OK away.

Now, when Visual Studio finished with our bidding, let’s take a look at what we’ve got…

Let me point out a few things.

First of all, perhaps the simplest Hello World app in the world :) Next, notice the npm folder in the project. This is going to give you a graphic way of managing your npm packages. Some people like to do things the graphic way. I personally never use this, but for some people it’s just your kind of thing. It actually works pretty slick too showing you all of your global modules, all of the modules that are installed, and visually differentiating the packages that have been added to your package.json file.

If you begin typing a dependency directly into the package.json, it gives you some Intellisense with an under-the-covers search of the npm repository, and it even helps you with the version…

I like that. I never type my dependencies in directly, but if I did, I’d certainly come to rely on it.

You can also use the npm dialog to install packages.

Again, nice, but I still keep a CLI open and execute npm install mypackage --save on my own. And of course, in that case, all of the installed packages are recognized by the tools, so I do enjoy having the visual indication that my package has been installed.

By the way, if you want to create a new Visual Studio Node.js project from an existing Node.js project that you have in your file system (perhaps recently cloned with git?) then check out my post Open an Existing Node.js Project in Visual Studio.

Using gulp for Deployment

We saw in the last post in this series how to wirelessly deploy your code to your device. You can keep doing it that way if you want, but there’s an easier way. Deploying your code is essentially a build task, and that’s what grunt and gulp are for.

NTVS also gives you a little bit of help with grunt and gulp. It’s hilarious that most people still refer to “grunt and gulp” whenever they talk about JavaScript task running frameworks. They do the exact same thing and I don’t imagine to many folks actually use grunt _and _gulp. Rather, most likely use grunt if they have to and gulp if they can. gulp is better hands down. grunt uses JSON files for configuration of tasks and gulp uses JavaScript. So, instead of composing gigantic JSON files to attempt to define what sort of tasks you need to run, you can stay in code and do whatever the heck you want or need. And gulp is supposedly way faster too, although I haven’t done any of my own tests.

Adding some gulp tasks to your app is easy. You just add a gulpfile.js to the project and add the gulp npm module both globally and at the project level.

The edref project has a little bit of gulp built in to deploy your code to your Edison device. Here’s that gulpfile.js content so we can talk about what gulp tasks look like…

/// <vs BeforeBuild='jshint' AfterBuild='deploy' />
var gulp = require('gulp');
var config = require('./config');

// JS hint task
// this is just a nice library for making sure your JavaScript syntax is all good
var jshint = require('gulp-jshint');
gulp.task('jshint', function () { // <--------------
gulp.src('./*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});

// deploy to the device
// NOTE: this will only deploy files at the root level; it is not recursive

var scp = require('gulp-scp2');
gulp.task('deploy', function () { // <----------------
return gulp.src(['*.{js,json}', '!gulpfile.js'])
.pipe(scp({
host: config.host,
username: config.user,
password: config.password,
dest: config.deployFolder
}))
.on('error', function (err) {
console.log('ERR: ' + err);
});
});

Notice the actual gulp tasks (where I put the <———— indicators). Those define what tasks are configured to run.

Now this next part I love. Visual Studio looks at the gulpfile.js at these tasks and adds them to a new pane called the Task Runner Explorer…

So jshint and deploy under Sub Tasks exist because they are defined in the gulpfile.js code.

Any time you need (or just want), you can right click one of those bad boys and hit Run and just run your tasks ad hoc individually. But also notice that under Before Build I have determined that the gulpfile.js/jshint task should run, and After Build the gulpfile.js/deploy task should run. That means that I can change a line of code, hit CTRL+SHIFT+B to build my project, and know that the targeted Edison (whether it’s on my desk or installed in a wall or gadget absolutely anywhere!) is going to contain the latest version of my project. That’s pretty awesome.

I’m working on another task as we speak that will fire off the node process for that app so your device will not only get its code, but start cranking on it as well.

Remote Debugging

Another scenario unlocked for us using the NTVS tools is debugging - even remote debugging. I’m thrilled about this one.

Note that you can also check out the official documentation for the remote debugging feature of the NTVS tools.

I did a little research online and found that most people working with devices are resorting to the classic console.log method of debugging. When you’re writing Wiring code for an Arduino, for example, you use a serial debug library that allows you to send messages back to the console in your Arduino IDE. You can then add something like…

Serial.println("Made it here!");

This reminds me of JavaScript development circa 1999 and by no means turns my crank.

What does turn my crank is running my project, perhaps watching a couple thing happen on my gadget, then hitting a breakpoint in my code in Visual Studio and being able to hover over any variables to see what their value is and hit F5 to continue. That’s an awesome dev scenario!

Here’s how to do it.

Write or open a Node.js project targeting your device.

You can clone http://github.com/codefoster/tweetmonkey if you’re looking for inspiration. You can see more about my good friend TweetMonkey at codefoster.com/tweetmonkey, but in short, he taps into Twitter’s streaming API and waits for tweets with the hashtag #tweetmonkey. When he see’s one, he comes to life, nods his head, squeaks, and clangs his symbols. My 3 year old loves it :)

Make sure you have a RemoteDebug.js deployed to your device

I like to include the RemoteDebug.js file in my project and check it into source so it’s ready to go for anyone that clones the project.

If you have the NTVS tools installed, you have this file. To see where it is, go to Tools | Node.js Tools | Remote Debugging Proxy | Open Containing Folder. Copy that file to your project or deploy it directly to your device. By the way, the gulp task that I include with the edref project (see later) copies all .js files, so if you put the RemoteDebug.js file in your project, it will get deployed automatically.

Execute your node app

You normally execute your app by remoting to your device (using something like ssh root@mydevice.local), changing to your project folder, and then executing the line…

node app.js

For remote debugging, you do it like this…

node RemoteDebug.js app.js

…and you should get some feedback like…

So you can see that the RemoteDebug.js file is launching a proxy for us using port 5858. And it introduces a term that was new to me - debuggee. I think I like it.

With that going, we’re ready for the next step.

Attach to Process from Visual Studio

In Visual Studio, go to the Debug menu and Attach to Process… and change the Transport to Node.js remote debugging.

Now, in the Qualifier field, enter tcp://devicename.local:5858 and check the Show processes from all users box. You should see your node process appear in the Available Processes.

Attach.

Now set a breakpoint.

And in the case of the app we’re working with here (tweetmonkey), send a tweet to hashtag #tweetmonkey and you should break at your breakpoint. As the French say, “Formidable!”

And, of course, in typical VS fashion, while broken, you can hover over JavaScript objects and check out all of their property values.

And you can open QuickWatch and enter any dynamic expressions you want and browse the results.

So, now you’re cruising!

The edref Project

There’s one last thing that I said I’d talk about, and that’s my edref project. There are a few things to do to set up a good, working Node.js environment in Visual Studio that will get you the kind of rich development environment I’ve lined out. It’s not a lot, but there’s not sense in doing it from scratch every time, so I’ve created a project called edref on GitHub that you can clone and get started right away. Feel free to fork and issue pull requests if you have ideas for how to improve it. I personally use this project for starting new hardware hacks, so when I find more efficient ways to do something, I’ll update the GitHub project.

The one thing I’d like to point out about the project is that the gulpfile.js is all set up to deploy your project to a remote device. You just have to fill out the config.js file with your particulars.

Conclusion

You should have what you need to not only write code for your Intel Edison, but write it in Visual Studio style! If you have any questions about this, please let me know in the comments. Consider this a living blog post still in that I’ll add edits here as I learn more about this fun device.

Happy hardware hacking!

This Week on Channel 9

This week I recorded This Week on Channel 9 with my good friend and colleague Steve Seow (@SteveSeow). Steve knows startups, and this week I invited him to join me as we present some pretty cool content about Docker, the VS Unity Tools, Node, home automation, the Intel Edison, and lots of other goodies. Have a look.

The Intel Edison

I am playing with the Intel Edison a lot these days. I’m a big promoponent of it, because I’m a big proponent of both power and simplicity. This device has enough power for whatever maker, robotic, gadgeteer project I can conceive of, and it’s all set up to easily run JavaScript via Node via Linux. This means I can use higher level libraries like Cylon.js. This means if I want to turn a motor, it’s easy. If I want to read accelerometer data from an ADXL377, it’s easy. If I want to include a Node module for storing temperature and humidity data in Azure, it’s super duper easy. I like easy - just not at the cost of power.

I’ll stop being wordy, though and just index the posts that I’ve creating (and am still creating) for the Intel Edison. Here they are.

Getting Started with the Intel Edison should help you pull it out of the box, mount the device to the dev board, flash the latest OS to the device, and get your toes wet writing code.

Writing JavaScript for the Intel Edison intends to pick up where the former left off and should help you get started writing Node.js apps using Cylon.js for the device.

Using Visual Studio to Write Node for Devices will bring a bit of awesome to coding for devices. You’ll have a rich development environment including remote debugging so you can actually step through breakpoints and watch your gadget react!

Flashing an LED when you get a Tweet (up next) will use what we’ve learned so far along with a Node.js module to hook into Twitter’s streaming API to turn your LED on for a couple seconds when you get a tweet.

Tweet Monkey is actually similar to the flashing LED sample I was going to do, but more fun. Would you rather see an LED flash or a monkey clanging symbols?! The real value in this tutorial is the JavaScript that combines calling in to the Twitter Streaming API with the using of the cylon library to talk to the monkey.

Command Monkey is Tweet Monkey’s older brother. Command Monkey is a fun and full-featured scenario where Cortana on the Windows Phone is used to tell the monkey to dance. This tutorial will teach you a pretty wide scope. You’ll learn to integrate Cortana, write a Windows Phone app using JavaScript, write a Node.js service on Azure, and how to communicate down to the device (the monkey in our case) using web sockets. It’s surprisingly little code overall.

Network IoT Devices (queued) is all about getting devices to form local or extremely broad networks that form huge logical apps and scenarios.

So you can actually check out posts in progress before I’ve polished them and called them done. Do please feel free to engage in the comments and offer feedback, advice, or questions.

Writing JavaScript for an Intel Edison

In my last article about the Intel Edison, I showed you how to take yours out of the box, and get it set up. Consider this article a follow-on. I’m going to pick up pretty much where the last one ended.

We actually wrote a little bit of code in the setup article, so you got a taste. Now we’re going to learn…

  • how to use the power of Node.js to bring in libraries and command our device
  • how to deploy code to the device wirelessly (zoing!)
  • how to use the excellent Cylon library to make our code elegant and expressive

Let’s start off in this article without employing the help of Visual Studio, and then my next article will capture the many productivity benefits of VS. It’s always nice to start at the base and climb up to awesome tooling. That way, we’re thankful for the conveniences it brings. :)

Using Node.js

Installing Node.js

I’m assuming your host PC is Windows. I’m running the technical preview of Windows 10 and it’s all working great. I like to live on the edge.

The easiest way to install Node.js is by simply clicking the big green button you’ll find at nodejs.org

You’ll see in the installation wizard, that you’re actually getting the NPM utility installed along with the Node.js engine. The installation should take care of a lot of busy work for you such as adding node and npm to your path so you can actually call it from the CLI. My CLI of choice, BTW, is PowerShell. To be clear, I’m talking here about installing Node.js on your host PC. Node and NPM should already be installed on the device if you flashed it according to the instructions in the last post.

After you have Node.js installed, we’ll walk through a few steps to create a new node project on your host PC. When we’re done with that, we’ll turn our attention to getting that code over to the Edison and running it there.

Creating the Folder and File Structure

Node.js projects have a pretty well defined, convention based folder and file structure. They’re very simple too - all of the metadata is in one spot. I don’t know where you keep your development projects, but I keep all of mine under c:\repos and I’ll start there. Watch the following video as I create a new project folder, generate an app package description file (package.json), and then create my initial app.js file…

As you can see, the npm init makes the creation of our package.json file very easy. The package.json file describes your node project and has a few purposes - the two most prominent that I can think of are a) it provides the metadata necessary in case we end up publishing this package to the node package store and b) it defines the project dependencies so that when the project is copied somewhere else, a simple command is all that’s necessary to actually go out and copy in all binaries necessary for the app to work.

Writing the Code

Now, in keeping with a simple workflow at first, let’s open app.js in Notepad++, and fill out the following…

var mraa = require('mraa');
var pin13 = new mraa.Gpio(13);
pin13.dir(mraa.DIR_OUT);
pin13.write(1);

This code depends on the mraa module, but if you followed my setup guide and flashed the Intel with the latest image, then you already have it. The mraa module maps the C libraries for interacting with the Edison’s hardware (the GPIO pins, the I2C bus, etc.) to Python and to JavaScript.

The code simply creates a new pin out of pin 13. Pin 13 is the one that conveniently has an LED on the dev board, so we don’t even have to plug anything in to see it. It then sets the direction of that pin to out. And finally, it raises the logic level of the pin by writing a value of 1.

Deploying Wirelessly

We saw in the last guide how to SSH directly to our device. If you gave your device the name “betty” like I did, then you’ve been provided a DNS name of betty.local which represents the IP address that your device was assigned on the network. If you’re not sure the device or the DNS name are working, just do ping betty.local from the CLI (replacing ‘betty’ with the name of your device of course). I’ve actually started pinging to discover the IP address and then using the IP address explicitly for SSH and SCP, because it takes a little time for the alias to resolve but hitting the IP address directly is snappy.

First, we’ll get our code copied to the device, and then we’ll SSH to the device in order to execute the code. It is also possible to simply execute the node app.js command remotely with SSH, but it’s fun to see what’s actually happening.

In this video, I’m going to SSH to the device, make a directory for our hellonode app, then jump back to my host machine, copy the files to the device (and specifically to that project folder) using SCP, and then back to the device to execute the app. The workflow can be simplified a bit, but I’m not arguing at this point. It’s pretty wonderful actually.

Notice the syntax of the SCP command. It wants scp @:. I do everything as the root user, so the is root and the directory is /home/root/.

You didn’t see anything happen there, but I did. My LED came on.

There are a few things that are cool about this. It’s cool that the mraa library preexists and makes communicating with the device pins so easy from a high-level language like JavaScript. Also, it’s great that we’re remoting and remote deploying our project wirelessly. This means that we can build something like an intelligent camera device, install it in a bird nest, and then remotely upgrade our software without disturbing the birds. That’s just the first example that came to mind.

Alright, now lets make our development really clean and easy by employing the CylonJS library.

Using CylonJS

CylonJS can be found at cylonjs.com. You won’t even need to go there to get the code, because we’re going to use NPM, but you may want to go check it out to get familiar with the project and eventually to research the documentation for whatever device and driver you’re using.
Let’s run through the steps to do something similar to our hellonode app above, but use the Cylon library.

In this video we will: create a project folder, create our app.js file with some sample code from cylonjs.com that will cause pin 13 to blink, generate a package.json file, install cylon.js via NPM using the --save parameter to add it as a dependency in our package.json file, then we’ll deploy to the device, and finally SSH to the device and execute the node program. You’ll actually see a video of the device with the LED blinking. Just a quick warning - we’re not only going to be holding off on Visual Studio at this point, but I’ve decided to use a CLI text editor for the hilarious factor as well as the convenience of showing everything in one window. I actually really like using the command line, but GUI’s are great too. As long as I don’t have to remove my hands from my keyboard, I’m a happy programmer.

EDIT: Thanks to Roberto Cervantes in the comments for pointing out a step that I should have called special attention to. In the following video, notice that after I scp the files to the device and then ssh to the device, I execute the command npm install. This looks into the package.json file that we just deployed to see what my project’s dependencies are, it goes out to the internet (to the NPM repository) to fetch the packages, and then it installs them. If you skip this step your app will have no idea what require('cylon') means.

A few things to note about this video…

  • My edit app.js command won’t work for you because that’s a special command line text editor that I use. I’m going to go ahead and assume you have your own favorite way to edit a text file. :)

  • Note that installing the cylon-intel-iot module added dependencies in the package.json for itself as well as for its dependencies. We actually never had to create the cylon module as a dependency. That happened implicitly because the cylon-intel-iot module knew that it needed it. That’s a cool thing about node modules - they each know exactly what they depend on and a single install command recursively takes care of business.

  • We copied over only the app.js and the package.json. We did not copy over the node_modules folder - you’ll notice that I deleted it before deploying. This is the right way to deploy project. You don’t check the node_modules in to source control and don’t copy it over in a deployment. Instead, you rely on the dependencies defined in your package.json file. On the deployment server, you execute npm install and if anything doesn’t get installed correctly, then you need to add it to your package.json file.

And now a bit about the CylonJS code. Here it is…

var Cylon = require('cylon');
Cylon.robot({
  connections: {
    edison: { adaptor: 'intel-iot' }
  },
  devices: {
    led: { driver: 'led', pin: 13 }
  },
  work: function(my) {
    every((1).second(), function() {
      my.led.toggle();
    });
  }
}).start();

Just like in our simpler hellonode app, we are doing a require right off the bat here. We are not, however, requiring the mraa library. Instead we’re requiring the cylon module. The cylon-intel-iot module will be invoked from within cylon and it will make calls to the mraa library. We risen up one layer of abstraction. The big benefit here is that we’re no longer writing device specific code. We could theoretically switch our Edison out for a Spark and it would just work.

The code block is, I admit, unnecessarily heavy if you’re just blinking a light, but ponder for a minute the elegance of this compared to the inevitable mass of imperative code that would occur were we doing anything more complicated.

There are a couple of Cylon terms that I should explicitly call out…

A Cylon robot is the device - the Edison or Beaglebone or Spheo or Tessel or any the other 32 or so devices that Cylon already has adaptors for. You define your robot with a connection and you use an adaptor (in the example it’s intel-iot).

A device in Cylon parlance is more like a component on the device. In our example above, the pin is a component and so it’s registered as a device. The important part of the device declaration is the driver. A driver is the interface that Cylon will use to interact with it. When the led driver is used, then the thing we’re calling led will have functions like .turnOn() and .turnOff(). This makes it so that our we only ever speak to our components with sensible language - you tell a servo motor .clockwise() and you capture a button press with .on('push',function(){}). Sensible is good in my book.

Besides declaring the connections and devices, we declare a function that is to run when the robot is finished with its setup. In this case, we’re using the built-in every function provided by the Cylon library to toggle the led every second. Easy peasy.

Well, folks, there you have it. This is the point in my learning that I felt like the gate was open and I was running free and wild. Oh, the myriad of devices to communicate with. Oh, the plethora of components. Oh, the possibilities.

I have a few more posts to write on this, but I’m keeping them all separate so I can get them out the door. All of these articles are indexed at codefoster.com/edison.

Please feel free to comment below if you have any trouble here. There’s a good chance I ran into the trouble you’re finding, and if I didn’t I’m willing to bang my head against the wall a bit with you - just a bit.

Taking Twitter by Stream

I found a number of examples of how to hook in to Twitter’s Streaming API using JavaScript (via Node.js) and every example I found was too hard. Not really hard, but too hard.

I find so much value in simple examples. It’s the whole reason I created codeShow.

Listen, bloggers. Most of the time, folks aren’t interested in your entire awesome solution. I know it’s awesome, but you have to consider the time it’s going to take for people to get their heads around a) what it is you’re trying to do (your domain), and b) all of the other stuff you’re doing that they don’t care about.

So, in the interest of keeping it simple, let’s take a look at a simple Node.js app for hooking in to the excellent streaming API by Twitter. Let’s take a look at it in 15 lines of code.

First, a note as to why you’d want to do this. Of course, you could do the atrocious - that is, hit twitter.com and scrape some results. Yuck. Or you could do the classic - that is, use the standard Twitter API and start asking it every 5 seconds if they have anything you’re interested in yet. But why do the atrocious or the classic when you could do the fantabulous? The fantabulous is hooking into the streaming API and then letting your app just sit there waiting for Twitter to call you saying “Hey, we found something you’re interested in.”

Here it is… in its entirety

var twitter = require('twitter');

var twit = new twitter({
consumer_key: 'PtSsmBwqSPtc8zQRDJ3GtbhKj',
consumer_secret: 'CsAsJ8fMDS3EPvhQhLawo8La6MwSiuEm1pAZbEDKDYULQFO513',
access_token_key: '176376243-RgYPr0nf9GWNe7ppxU5fLq9KXbmu5m2AT3qB0Box',
access_token_secret: 'P0V8b94x0Csmw41GubwfI45h9p4gKPNAIWNtMauFtz8vT'
});

twit.stream('filter', { track: 'dog' }, function (stream) {
stream.on('data', function (data) {
console.log(data.text);
});
});

The above code has a simple dependency on a rather popular Node.js module called twitter. I’m obviously assuming you are familiar with installing Node.js modules here, but that’s pretty easy to pick up.

The magic about the above code is that a) it does what it’s supposed to and b) it doesn’t do anything else.

The documentation for the twitter module is pretty sparse, but you don’t need to know much about it. You really need the documentation for the Twitter Streaming API. That will teach you what a filter type stream is, how to add a search term as a track, and how to handle the data that is returned.

That’s all for now.

(and yes, those keys are obfuscated :)

Open Existing Node.js Project in Visual Studio

Working on a coding project inside of Visual Studio is hugely helpful. VS does so many things to support the developer, that I myself (and millions of others) define it as indispensable. Whether I’m writing C# or JavaScript, I still want to do it in Visual Studio.

I have a lot of Node.js code on my box and occasionally I’ll get into a situation when I have an existing Node.js project (one that I didn’t create initially using Visual Studio), and I want to open it in VS.

When you create a new Node.js project in Visual Studio, it gives you the basic files - app.js, package.json, and README.md - and then it gives you a .njsproj file. That’s the file that lights VS up with all of the additional help that’s specific to Node.js. That’s the file we essentially need to create in an existing project, but how? It’s not exactly a new project, but according to Visual Studio’s definition, it’s not an existing project either.

I’ll show you how. But first, you have to have Visual Studio (I’m running the free Visual Studio Community 2013 with Update 4) and the Node.js Tools for Visual Studio.

First, open Visual Studio and choose File | New Project…

Under the Templates section you should be able to expand a JavaScript section and then choose Node.js.

On the right, you will see a big list of project templates, and notice the second one (it’s the second on my list at least) - From Existing Node.js code. That’s the one. Hit it.

The values in the 3 boxes on the lower end of the box - Name, Location, and Solution Name - by the way, are used to populate default values on subsequent screens, but you’ll have a chance to change them. I recommend you put the name of your project in the Name field and the path to it in the Location.

Then hit OK.

The first wizard screen prompts you for the location of your existing Node.js project. If you populated the Location field on the New Project screen, then this will already be set. The rest of this screen is self-explanatory.

The wizard next guesses what is the entry point. If it’s not right then point it to the right one.

Finally, you need to indicate the name of the .njsproj file, and again it’s going to pull a default from the New Project screen if you filled that out.

And there you have it. You’ve essentially gotten a .njsproj file created where it should be. If you created this new project from the File menu like I did in my example, then your new Node.js project is inside of an unsaved solution file, so when you close Visual Studio or the solution, it’s going to prompt you to save it. The other approach - if you already had a solution - would be to open it, right click the solution file, and then choose New Project from the context menu.

Have fun with Node.js!

Project GoChute

This is a live post, so be sure to check out the addendums at the bottom.

I haven’t entirely given up on my GoChute idea, but it has slid down the priority list somewhat. I’d better explain.

Let me tell you what my GoChute idea was/is and where I’m at on it.

The GoChute is an attachment for a GoPro camera that allows a person to use their GoPro for a mega, aerial selfie. Sure, you could shell out a few hundred or maybe thousands of dollars for a drone, but the GoChute will get you the coveted bird’s eye view on the cheap. It would work by allowing you to throw or launch the complete unit high into the air. It would detect the apogee of travel, deploy a parachute, and then drift gently back down to earth while taking your video.

I’m a big fan of the GoPro cameras. I have a GoPro HERO3+ Black edition and I have used it for everything from checking a spinning boat propeller to playing at the water park with my family to recording CodeChat episodes.

The rugged and waterproof case for the GoPro is certainly one of its big values, but the biggest arguably is the wide array of mounts available. You can spend a few bucks and get your GoPro on your head, on your chest, on you bumper, on your windshield, on your harness, on your roll bar, on your sailboat rail, or just about anywhere else.

I decided to take advantage of this with the GoChute.

The GoChute idea is fun because it’s a good combination of hardware and software. Here’s the basic hardware…

This package was designed in SketchUp. I found a GoPro adapter in the 3D warehouse that attaches to the camera housing itself, and then proceeded to redesign the entire box.

You can see the hinged lid on the top and holes on the side for securing parachute lines. Here’s the other side…

On this side, you can see the parachute deployment latch and a couple of holes for status LED’s to poke through.

Here’s an exploded view of the latch…

The latch itself is on a small hinged joint. A servo motor mount allows me to mount the motor that is going to pull the latch when it’s time for the parachute to deploy. I’m counting on the lid being under pressure (likely by use of a spring) in order to keep the lid closed securely and to eject the parachute well once the latch is tripped.

This entire package would be 3D printed in 3 parts - the box, the small latch, and the lid.

Inside the package would reside a smart device for reading sensors and figuring out how to behave (when to deploy the chute mainly). The plan is for that smart device to be an Intel Edison, because of its small form factor and because I have one on hand, but a variety of devices could be used.

According to the original plan, the device would require little more than an accelerometer and a battery for power.

Before I printed the package, I decided to get the electronic circuit prototyped and prooved out. And upon doing, I ran into a snag - a snag that has not quite killed, but certainly postponed the project. I must confess, the snag is entirely due to the amount of time between me and my high school physics courses.

The first thing to do in setting up the circuit was to wire up an accelerometer. Here’s the ADXL335 that I ended up using…

In case you’re interested in this stuff and don’t already know, there are basically two kinds of accerometers you can use for a project - analog and digital. The ADXL335 is analog. Analog accelerometers are easier to use and sometimes offer more resolution. With an analog accelerometer, after you’ve accomplished the simple task of providing it 3.3V power and ground, you wire three pints (for each of the three axes in our 3D world) to your smart device and each has a voltage value that represents the amount of acceleration (g-force) acting on that axis at any given moment in time. So reading an analog accelerometer is a simple matter of calling a function like .analogRead() or its equivalent on each of the three inputs.

When you have an accelerometer installed into a device securely and permanently, then it’s orientation may have some meaning. If you put it in a car, then you may care, for instance, about the fact that X is the forward/backward axis, Y is the side to side axis, and Z is up and down. In this project, however, who knows what the orientation of the device is going to be in the air. It will likely be spinning all around. Especially considering the fact that the plan involves launching this from a vertical slingshot.

So the values of acceleration on the individual axes matter not. What matters is the overall acceleration on the unit. It didn’t take much web research to remind myself of the formula…

So, let me go ahead and list some simple code for determining this. This is JavaScript. If you’re interested in writing JavaScript on a device, then head on over to my Setting up an Intel Edison post and see how I got here.

var cylon = require('cylon');

cylon.robot({
connection: { name: 'eddie', adaptor: 'intel-iot' },
devices: [
{ name: 'x', driver: 'analogSensor', pin: 0 },
{ name: 'y', driver: 'analogSensor', pin: 1 },
{ name: 'z', driver: 'analogSensor', pin: 2 },
]
}).on('ready', function (eddie) {
every((0.05).second(), function () {
var m = mag(eddie.x.analogRead(), eddie.y.analogRead(), eddie.z.analogRead());
});
}).start();

function mag(x,y,z) {
return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2));
}

Cylon is a JavaScript library that makes working with devices much easier. It happens to have a bridge for the Edison, so it’s all very easy to work with.

In the above code, I’m calling my Edison eddie and I’m polling the analog pins every 20th of a second and applying the aformentioned formula to determine the magnitude.

Then, I took my Edison, accelerometer, and a USB battery pack for power and rubber-banded it all together and threw it in the air and then caught it. Do you want to see the results? I certainly did. I have to say, I was surprised. Will you be?

Here’s the overall acceleration (the magnitude of all axes)…

There was a value on the pins when I let the unit rest, and I subtracted that from all subsequent values.

I spend considerable time studying this chart with my wife (who is much smarter than me) and I have to admit there are still some parts that are a bit baffling. Here’s what (I think) I do know now…

  1. The ramp up before the flat line (from about 105 to 109) is my throw. That’s me adding acceleration to the unit.
  2. The flat line from 109 to about 122 is the span after leaving my hand and before catching it.
  3. The spike to a value of 800 at 123 or so is the moment the unit landed back in my hand and there’s a small rebound (bounce) at about 125.

Here’s what I’m certain I still don’t know about that chart…

  1. Why did the acceleration drop around 37 when (I believe) I picked the unit up from the table?
  2. Why did the acceleration drop between 97 and 106 just before I tossed the started my throw?
  3. Why is the steady value from 1 to 37 the same value as from 109 to 122 when the unit was in the air and being affected by gravity?

I may be reading the chart all wrong, and would certainly welcome your comments below.

In attempting to understand, I tweeked my code to create a delta between the last magnitude reading and the current one - a delta. The chart for the acceleration delta is perhaps a bit easier to understand…

But the biggest discovery I got out of reading these charts was that…

I’m not going to be able to detect the apogee using an accelerometer.

My error was in thinking that the acceleration force on the unit would diminish as it ascended, zero out at its apogee, and start increasing again as it descended. Perhaps I was making a noobie mistake and thinking of the unit’s velocity. The fact (as I understand it now) is that straight line from 109 to 122 means there’s nothing at all that changes at the peak of the unit’s travel, and thus no way for me to launch my parachute with this data alone.

I researched how model rockets determine the same thing, and sure enough I discovered that they tend to use altimeters or human spotters with calculators (that’s a different kind of geeky).

I did have one idea as to how to make this work. I could do a little bit of math and add up the amount of energy that was put into throwing the unit. Because the resistence to that energy (gravity) is constant, I should be able to do a decent job of calculating how long this thing is going to be in the air, cut that in half and launch the parachute based on timing. I’m not exactly excited about doing the testing that that method requires, and that’s why this project is sliding.

Thanks for reading!

Addendum (2014-12-04)

Actually, the project is back on :) I’ll explain.

I love the process I had to go through to discover that an accelerometer would not work. I don’t mind not knowing things. I mind not learning things!

I attended a meetup of the KingMakers in Redmond the other day and had a good conversation with someone with some hobby rocket experience. He said that it’s very common to use barometric altimeters to measure altitude and that the resolution is very good - something like 1 foot! Wow. I would not have guessed. I quickly considered an altimeter, but dismissed it almost as quick thinking that the resolution would be too poor. After learning this, though, it didn’t take me long to find the MPL3115A2 from Adafruit.

This bad boy is capable of .3m accuracy and even comes with a thermometer for temperature readings.

So with new information in my quiver, I’m back in the game. Look for more here on the GoChute project as progress unfolds.

Setting up an Intel Edison

This is a guide to getting started with the Intel Edison.

Intel has published a guide for getting started with this device as well, but I wanted to get everything into one place, tell it from my perspective, and smooth over a couple of the bumps I hit on the way. Let me know with a comment below if you have any questions.

I like to keep things simple, so I’m going to help you get started with the Edison as easily as possible.

In a subsequent post, I’m going to show you how you can very, very easily start writing JavaScript to control your Edison. You won’t have to deal with Wiring code, you won’t have to install the Arduino IDE (argh!), and you won’t have to install Intel’s attempt at an IDE - Intel XDK IoT Edition. You’ll be able to use Visual Studio, deploy to the device wirelessly, and then have plenty of time when it’s done to jump in the air and click your heels together.

In another post, I’m going to show you how to use Azure’s Event Hub and Service Bus (via a framework called NitrogenJS) to not only do cool things on one Edison, but to do cool (likely cooler actually) things on multiple Edisons, other devices, webpages, computers, etc.

Introducing the Edison

The Edison is tiny. It’s the size of an SD card. Despite its size, though it has built in WiFi and Bluetooth LE and enough processor and memory oomph to get the job done.

The design of the Edison is such that it’s pretty easy to implement a quasi-production solution. It’s not always easy getting a full Arduino board into your project, but the Edison is almost sure to fit.

I’m not the only one that’s excited about this System on a Chip (SoC) either. Sparkfun.com is too. They made a great video introducing the technical specs of the Edison and showcasing their very cool line of modules that snap right on to the Edison’s body. Here you can see a few of those modules piled up to produce a very capable solution…

That’s the kind of compact solution I’m talking about. The only problem is that at the time of writing, the modules are only available for pre-order.

Not to worry though, there are a couple of other ways to interface with the Edison and get working on your project. The recommended way is by using the Arduino dev board. This is what the Edison looks like when it’s snapped to the dev board.

This dev board explodes all of the functionality packed into the Edison and makes life easy. It gives you USB headers, a power plug, GPIO (general purpose input/output) pins, a few buttons, and a micro-SD card slot.

There’s another dev board available for the Edison - a mini board - but it’s less used because it requires soldering and doesn’t offer as many breakouts. If you’re looking for compact, you can just wait for the Sparkfun modules I mentioned. Here’s the Edison mounted on its mini board…

In this guide, I’ll take you end to end with getting the Edison setup on a Windows machine. I am not prepared to detail instructions for Mac/Linux, but Intel did a good job of that on their guide anyway. I’m going to mention the physical setup of the device, installation of the drivers (on your host PC running Windows), then walk you through flashing it with Intel’s custom Yocto Linux image and training it to connect to Wifi. When we’re all said and done, we’ll never have to plug the Edison into our host PC via USB again. We’ll be able to wirelessly deploy software and otherwise communicate with the device. Finally, we’ll write a simple bit of code, but in a follow up post, we’ll get crazy with software, because that’s what we do.

Physical Setup

Physically setting up the Edison once you’ve pulled it out of the box is pretty straight forward. I’ll assume you’re starting with the Arduino dev board.

Add the plastic standoffs to the dev board if you’d like. They’re good for keeping Edison’s sensitive underbelly from touching anything conductive and creating a dreaded short.

Next snap the Edison chip onto the board. You can put the tiny nuts onto the posts to hold the chip on, but I choose to rely on the solid friction fit instead.

Flashing

Before your Edison is going to do anything exciting, you’ll need to connect to it and flash it with the latest version of the Yocto Linux distribution that is provided by Intel. At first, it has no idea how to connect to a Wifi hotspot, so we’ll have to establish a serial connection. It’s quite easy actually.

Intel’s guide does a decent job of walking you through these steps, but again, I’m going to do it on my own to add my own perspective and lessons learned.

The guide asks you to plug in both USB cables. That will work, but it helps to understand why. One of the USB micro plugs (the one closest to the power plug and the larger USB port) is a host plug that will a) power the Edison via USB and b) will cause a certain directory from its file system to appear in Windows Explorer as a drive. The other USB micro plug (the one closest to the edge of the board) is a serial connection that will allow you to establish a 115200 baud serial connection before Wifi is established.

What I prefer to do is power the Edison with a barrel connector, and then just use one USB cable plugged in to whichever header I need. This works well especially since one of them is only need for one step upon initial setup - to flash the device. I have a USB to barrel connector, so I can simply plug my Edison into a USB battery pack and emphasize that it’s completely wireless.

Do make sure the itty bitty switch next to the USB micro plugs is switched toward the USB micro plugs.

Download and install FTDI drivers. First, you need to download and install the FTDI drivers which allow your host computer to communicate with the USB header on the Edison. The file you download (“CDM…”) can be directly executed, but **I had to run it in compatibility mode **since I’m running Windows 10. I won’t insult your intelligence by telling you how to hit Next, Next, Finish.

Download Intel Edison Drivers. Now you need drivers for RNDIS, CDC, and DFU. It sounds hard, but it’s not. Go to Intel’s Edison software downloads page and look for the “Windows Driver setup”. This downloads a zip file called IntelEdisonDriverSetup1.0.0.exe. Execute the file and comlete installation. The download goofed up for me in IE11 on Windows 10, so if you run into that, go to the link at the bottom of the page that says it’s for “older versions”. The download for that same file is there and it’s not an older version.

Note: In case you want to know, the RNDIS (Remote Network Driver Interface Spec) is for virtual Ethernet link over USB, the CDC (Composite Device Class) is a standard for recognizing and communicating with devices, and DFU (Device Firmware Upgrade) is functionality for updating firmware on devices.

**Copy flash files over. **With these two driver packs installed, you should have a new Windows drive letter in Explorer called Edison. This is good, because that’s where you copy the files that will be used to flash the device. Go back to the Intel Edison software downloads page and locate and download “Edison Yocto complete image”. Save it local and unzip it. Now make sure the Edison drive in Windows Explorer is completely empty and then copy the entire contents of the zip file you just downloaded into that drive.

Connect to the device using serial. Since we’re finished copying files to the device and ready to connect to it over serial, we need to switch the USB cable from the inner port to the outer port. Do make sure you have the USB to barrel connector in place so you get the reassuring power light on the board.

The Intel guide walks you through using PuTTY (a Windows client for doing things like telnet, SSH, and serial connections). I’m a command line guy, so I use a slightly different approach using PowerShell which I’ll present. You can choose which you like better.

Go to the PuTTY download page, download plink and save the resulting plink.exe file into some local directory. I use c:\bin. Now you’re ready to use PowerShell to connect to a serial port. Very cool.

Note: plink in PowerShell does something goofy with the backspace key. It works, but it renders ?[J for each time it’s pressed. If you know a way around this, let me know.

Before you connect, you have to see what the COM port is for the Edison. Go to Device Manager and expand the Ports (COM & LPT). Now look for USB Serial Port (COM_X_). Mine is COM5.

Here’s the line I use to connect (actually, I put a plink function in my $profile to make it even easier… ask me if you want to see how)…

. c:\bin\plink.exe -serial COM5 -sercfg 115200,8,1,n,Namely

…if you saved your plink.exe into a different location or if your COM port is different then change accordingly.

Execute that line and then hit enter a couple of times. You should find yourself at a root@edison:~# prompt. That’s good news. Your on the device!

Initiate the flash. To flash your Edison using the files you copied into the drive, you simply type reboot ota and hit Enter. Watch your device do a whole bunch of stuff that you don’t have time to understand, and rejoice when it finishes and returns you to the login prompt. Your login is root and you don’t have a password. You should be sitting at root@edison:~# again.

Setup wireless. You have a full Linux distribution flashed to your Edison now, and it’s ready to talk Wifi. You just have to configure a couple things. Namely, you have to a) give your Edison a password (technically, provide a password for the root account), b) make sure your host PC is on the same network as your Edison, and c) provide your SSID and password. The first point is one thing the Intel guide skips - the need to set a password on the root account. If you don’t do it, you won’t be able to SSH to the device over Wifi. To initiate, execute configure_edison --setup. You’re prompted for a device name. I like to name mine (mine are called Eddie and Betty) so they’re easier to differentiate in terminal windows. I provide easy passwords for mine, because I’m not exactly worried about getting hacked. Next, you’ll be prompted to setup up Wifi. Follow along, choose the right hotspot, and enter the Wifi password when prompted.

Connect to the device using SSH over TCP/IP via the Wifi. Let’s get rid of this silly hard link and serial connection and join the modern era with a Wifi connection. Disconnect from the plink connection using CTRL+C. You can pull that USB cable out of your Edison’s dev board too. Your Edison is now untethered! Well, except for power, but a battery could take care of that.

Now again, I’ll diverge from the Intel guide here so I can stick with the command line. I use Cygwin on my box to allow me to SSH via PowerShell. I like it a lot. EDIT: Thanks to @palermo4 for pointing out that it’s not Cygwin that’s giving me this functionality, but rather my install of GitHub for Windows and the fact that I subsequently added GitHub’s bin folder to my path in Windows. Simply install GitHub for Windows and then go to your Environment Variables in Windows, edit the PATH variable, and append your bin directory to the end. On my system, it’s at C:\Users\jerfost\AppData\Local\GitHub\PortableGit_7eaa994416ae7b397b2628033ac45f8ff6ac2010\bin; I’m guessing yours is different :) After adding this, test it by typing SSH<Enter> in PowerShell and see if you get something besides an error.

You can use this approach, or you can go back to the Intel guide and use the PuTTY approach.

Before you can SSH to your device, you have to figure out what it got for an IP address. But the Edison has done something nice for you there. It created name.local as a DNS entry, so to connect to an Edison with the name eddie, you can simply use eddie.local. Mine is resolving to 192.168.1.9. If this doesn’t work for you, you can always log in to your router and find out what IP address was assigned to it or you can go back to the serial connection and type ifconfig at the prompt and look for the wlan0 network and see what address was assigned.

From my PowerShell prompt, I can just type ssh root@eddie.local. You’re connected to your Edison over Wifi now, and you’re so very happy!

Ready to Write Code!

From here, you’re ready to write some code. I’m going to write an extensive blog post on the topic, but for now, let’s get at least a taste.

First, make sure you’re SSH’ed to the device. So run that same ssh root@eddie.local command and sign in with your password.

Hello World! First things first. Let’s greet the world using JavaScript (via NodeJS). Type node and hit Enter and you should be at a > prompt. You’re in NodeJS… on your Edison. Man, that was easy.

Now type console.log('Hello World'); and hit Enter. There you have it.

Hit CTRL+C twice to get back to your Linux prompt.

Blink the light, already! You haven’t gotten started with an IoT device until you’ve blinked an LED, so let’s get to it. Still SSH’ed to your device, execute each of these lines (each at the prompt) followed by Enter…

node //enter NodeJS again
var mraa = require('mraa'); //create a reference to the built-in mraa library (which provides easy access to hardware capabilities)
var led = new mraa.Gpio(13); //setup a variable for pin 13 which also happens to be an LED on the board (how convenient)
led.dir(mraa.DIR_OUT); //tell pin 13 that it should act as an _output_ pin for now
led.write(1); //turn the LED on
led.write(0); //turn the LED off

And this is full-on JavaScript, so you can go crazy with it (recommended). Try this…

var state = 0; //create a variable for saving the state of the LED
var blink = function() { state = (state==1?0:1); led.write(state); setTimeout(blink,500); } //create a function that changes the state, waits 500ms, and then calls itself</span>
blink() //start blinking

The light should be flashing on and off, but your state of bliss should be sustained high!

It’s obviously not sustainable to write our code at the prompt, so stay tuned for my next guide on writing code for your Edison.

Have fun!

The Azure CLI

At the time of this writing, there are two Azure portals you can use.

To get to the main, full-featured, current Azure portal, you browse to manage.windowsazure.com in any modern browser, and it looks like this…

The new portal is already available for you to play with and get familiar with, and it’s a good thing too since it takes quite a bit of getting used to. Once you grok it, though, I’m pretty sure you’ll like it better. You get to the new portal by browsing to portal.azure.com. Here’s what it looks like…

Both of these are works of modern, web art and very functional in my opinion. I love the current portal, and now that I’m accustomed to it, I love the new portal as well.

But I would like to get to the place where I have little to no need for the portals. I would like to instead to be utterly dependent on the command line.

I started some time back on the PowerShell command interface for Azure and it’s very well made. I had a hard time getting to it though. I suppose it was the long commands - the PowerShell syntax. Although it’s quite descriptive and offers good tab completion and documentation, I still found it a chore and kept at my work in the portal.

I had a glance some time ago at the node tooling for Azure as well, but didn’t really give it a fair shake. Now I’m shaking it like crazy and really excited. Check out some of these things you can do…

Check out which Ubuntu images I can use for creating a VM…

The following will generate a list of Azure VM images and allows me to pipe to a regular expression to pull out just the stable (LTS) Ubuntu images of a certain version (14.04.1). It’s also possible to add a --json property to the request and get this data back in JSON format.

azure vm image list | grep 'Ubuntu.*14_04_1.*LTS'

Create an Ubuntu Linux VM from one of those images…

Once I’ve chosen the image I want to start with, I simple call the following to create a new VM in the West US region. I add the -e parameter to add ssh capability so I can ssh into the machine when it’s finished.

azure vm create -l 'West US' VM_NAME b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-trusty-14_04_1-LTS-amd64-server-20141110-en-us-30GB codefoster -e

Now let’s fetch a list of my VM’s and see the new mynewubuntumachine in there…

By the way, if you’re like me and like staying in the command line interface, try installing Cygwin. It runs great in PowerShell and allows me immediately after creating this VM to ssh into it like so…

I’d rather that machine not start charging me for compute, so let’s shut it down and make it free (except for a little bit of storage… pennies)…

That’s better.

What else can we do with the azure-cli? Oh, man. Glad you asked. Let’s create a quick Azure Mobile Service, add a table, and then use some PowerShell candy to start writing and reading records.

Creating a Mobile Service…

First, we create the service like the following where gg4p4pzmfi is simply the name of my particular SQL Server. I already have it, so I may as well use that instead of creating a new one. My service is actually going to be called “cfms”.

azure mobile create --sqlServer gg4p4pzmfi cfms

Then we create a table. Let’s just punt and call it widgets. In order to show interactions with the table via simple HTTP commands, I’m going to open up the insert and read permissions so I don’t have to create authentication headers in my HTTP calls…

azure mobile table create cfms widgets -p read=public,insert=public

And there we have a service with a table ready for us. Now, in case you’ve never noticed, PowerShell natively allows us to use curl to do web requests, but curl is not really installed. Instead it’s a simple alias to the Invoke-WebRequest method in PowerShell. I chose to write the following functions into my PowerShell profile so it’s always available to me…

Function get ($uri)
{
(Invoke-WebRequest -Uri $uri).Content;
}

Function post ($uri, $body)
{
(Invoke-WebRequest -Uri $uri -Body $body -Method Post -ContentType "application/json").Content;
}

So now we can write a record into our new widgets table like so…

post [http://cfms.azure-mobile.net/tables/widgets](http://cfms.azure-mobile.net/tables/widgets) '{"name":"widget 1"}';

Do notice that the response we got back from this post included the actual inserted object complete with the GUID that Azure Mobile Services tacked on to it. In case you’re not already familiar with Mobile Services, you should also take note that we didn’t schematize this table when we created it. Instead, we simply created an object with a name property and let Mobile Services handle that for us.

Now, a get from the same table should show us our widget 1 record, and in fact it does…

I love how simple and elegant a solution this is.

There’s obviously a whole lot more we can do with azure-cli that I won’t take the time to detail. But there’s one more thing you should see - the inline help. For any command, simply tack on -h and you will get good information about the various possible parameters you can use. It’s contextual too. If you type azure -h, you’ll see all of the high level options for the azure-cli tool, whereas if you type azure vm -h, you’ll see specific commands for working with VM’s.

The azure -h is great for giving you an overview of what the tool will do.

I hope you have as much fun with this as I have already.

To get started, visit this page to see instructions on installing the tooling.