MQTT on Tessel

9/24/2014– Jon McKay

Using MQTT on Tessel

MQTT is a lightweight publish/subscribe protocol designed for machine to machine communication. The architecture features one central server that manages the subscriptions and publications from each of its numerous clients. Clients can publish data without having to be aware of who is subscribed (much like Node’s EventEmitter class).

source: Eurotech

MQTT is also designed to require minimum protocol overhead for each packet in order to preserve bandwidth for resource-constrained embedded devices. It’s a really simple framework for managing mesh networks of TCP-enabled devices.

Tessel-MQTT Compatibility Backstory

As far as I could tell, there is only one MQTT implementation in Node (surprising, right?!) and it’s really well maintained. Up until a few weeks ago, the library couldn’t run on Tessel due to a couple of Node and JS incompatibility issues. The biggest problem was the use of Function constructors, used primarily for speed improvements, which isn’t supported on Tessel yet.

In JavaScript, the Function constructor accepts a string of JavaScript code which it processes into an actual function:

var f = new Function(foo, bar, “console.log(‘the arguments are’, foo, bar)”);
f(‘a trivial’, ‘example’); // prints ‘the arguments are a trivial example'

It’s often used as a faster way to template a function, replacing Function.prototype.bind which runs abnormally slow on V8.

Tessel’s runtime translates JavaScript to Lua on a host PC before being pushed to Tessel and run on a Lua Virtual Machine. We’ll need to push compilation functionality over to Tessel before Function constructors (or eval) can work on the device. Tim has made stready progress on a compiler written in C (as opposed to JavaScript) that will reside on Tessel itself and compile JavaScript to LuaJIT bytecode. But it isn’t quite ready yet, so we looked for another way around the issue.

Matteo Collina, one of the primary maintainers of the MQTT.js library, and I started a discussion about the MQTT library’s compatibility with Tessel. He was kind enough to accept a pull request that replaced the Function constructors so that we wouldn’t have to wait for the C-based compiler to be complete to use MQTT on Tessel. I just had to fix one more issue with Buffer parsing and the library worked without a hitch on Tessel!

Code Example

Tessel can act as either an MQTT server or a client, and the client code is impressively simple in practice. In this code snippet, I publish the current temperature to an MQTT server every five seconds:

var mqtt = require('mqtt')
  , host = '192.168.8.102'
  , port = 1883
  , client = mqtt.createClient(port, host, {keepalive: 10000})
  , tessel = require('tessel')
  , climate = require('climate-si7020').use(tessel.port['A']);

climate.on('ready', function ready() {
  console.log('climate ready');
  setInterval(function() {
    climate.readTemperature(function(err, temperature) {
      if (!err) {
       // You can only publish strings
        client.publish('temperature', temperature.toString());
      }
    });
  }, 5000);
});

You can find the entire example on this Github Gist.

If you have a project that requires the use of multiple data gathering clients interacting through a single server, consider trying out MQTT because it’s one of the simplest protocols for M2M communications.

-Jon

How-to: Adding Buttons to Tessel

9/24/2014– Kelsey Breseman

A number of users have requested a button module on Tessel. We welcome this and other module suggestions here, but in the meanwhile, I thought you’d find a tutorial on adding your own buttons (of any size and shape) useful.

I’ve put this up on the Projects Page, so I encourage you to also check it out, access the repo, and comment there!

But as long as I’m going into the details of how buttons work, I thought you all might appreciate it on the blog.

Quick start: I just want a button.

Your button should have two wires sticking out of it. Plug in one side to ground, and the other to pin G3.

Install:

npm install tessel-gpio-button

Use:

var tessel = require('tessel');
var buttonLib = require('tessel-gpio-button');
var myButton = buttonLib.use(tessel.port['GPIO'].pin['G3']);

var i = 0;

myButton.on('ready', function () {
  myButton.on('press', function () {
    i++;
    console.log('Press', i);
  });
});

Congratulations, you now have a button!

How it works, and why

Why add a button over the GPIO?

Buttons are a nice, easy way to make your project interactive. Tessel comes with API access to the Config button on the board. For many use cases, this is enough. But perhaps you want more buttons, or buttons with a certain look or feel. That’s where this tutorial will come in handy.

What is a button, in terms of circuits?

Electrically, a button is nothing more than a switch. One wire goes into the button; one wire comes out. When the button is pressed, the wires are connected. When not pressed, the wires are not connected.

Making a button talk to Tessel

Tessel communicates over 3.3V. That means that its pins operate between 0V and 3.3V. For a digital pin, 3.3V evaluates to “high” or 1 (truthy), and 0V evaluates to “low” or 0 (falsy).

Tessel has six digital pins along the GPIO bank, marked G1-G6. Each of these pins is pulled high (3.3V) by default. In order to change the state of these pins from high to low, all you have to do is connect a digital pin to ground (GND).

If you have a wire, you can try it out– plug in a wire (ideally black, for ground) in to the GND pin on Tessel’s GPIO bank. While running the code below, try sticking the other end of the wire into G3:

// tutorial/polling-read.js
// Read Tessel's GPIO pin G3 every 100ms

var tessel = require('tessel');
var myPin = tessel.port['GPIO'].pin['G3'];

setInterval(function readPin () {
  console.log(myPin.read());
}, 100);

You should see a stream of ones while the wire is not plugged in, and a stream of zeroes when it is plugged in.

Okay, now let’s try it with a button. It’s basically the same thing. Unplug your Tessel (it’s bad practice to mess around with wires while your Tessel is powered). Your button should have two wires sticking out of it. One of them should plug into GND; the other into pin G3.

Run the same code, and try pressing the button. You should see zeroes when the button is pressed, and ones when the button is not pressed.

Button events

Tessel has events for its pins. It fires an event each for rise, fall, and change.

Since the signal falls to low when the button is pressed, and rises to high when the button is released, it seems like you should be able to just use pin.on(fall, function () {}). Let’s try it and see what happens:

// tutorial/simple-event.js
// Logs a message each time the pin falls

var tessel = require('tessel');
var button = tessel.port['GPIO'].pin['G3'];

var i = 0

button.on('fall', function buttonPress () {
  i++;
  console.log('You pressed the button!', i);
});

If you have a really nice button, this might just work. However, if you have a cheap button like mine, the fall event will be emitted more than once per button press. This is because you are dealing with a mechanical system, and the electrical contact is actually bouncing a little bit on contact and messing up the signal. You can read about this phenomenon here.

In order to correct this problem, we need to do some software debouncing.

Debouncing can be a very complicated problem if you need the ability to read the button several times a second (read a few approaches here). However, for most applications, you can simply reduce the rate at which your events can fire.

Let’s try adding a delay timer to the event:

// tutorial/debounced-event.js
// Logs a message at button presses that are sufficiently spaced

var tessel = require('tessel');
var button = tessel.port['GPIO'].pin['G3'];

var delay = 500; // Let's try every 500ms
var ready = true;

var i = 0

button.on('fall', function () {
  if(ready) {
    buttonPress();
  }
});

function buttonPress () {
  i++;
  console.log('You pressed the button!', i);
  
  // Set a delay timer
  ready = false;
  setTimeout(function () {
    ready = true;
  }, delay);
}

500ms worked well for my button, but feel free to adjust the delay and see how long it takes for your button to stop bouncing.

Wrapping the events

For the sake of consistency, I’ve set up index.js of this folder the same way we set up every module, to emit an event on press. press and release are individually easy, but harder to have both due to our simple debouncing method. I’ve left that as an exercise for the reader (PRs welcome).

Here’s some example code requiring index (or just npm install tessel-gpio-button):

// examples/button.js
// Count button presses

var tessel = require('tessel');
var buttonLib = require('tessel-gpio-button');
var myButton = buttonLib.use(tessel.port['GPIO'].pin['G3']);

var i = 0;

myButton.on('ready', function () {
  myButton.on('press', function () {
    i++;
    console.log('Press', i);
  });
});

Multiple buttons

Say you want more than one button. Maybe you’re making a game controller, or a musical instrument or something. So you have several buttons to connect.

All you have to do is connect one side of each to ground, and the other side to a different digital pin.

Then make different instances for each button. Like this:

// examples/two-buttons.js
// Log button presses from two different buttons

var tessel = require('tessel');
var buttonLib = require('tessel-gpio-button');

var button1 = buttonLib.use(tessel.port['GPIO'].pin['G3']);
var button2 = buttonLib.use(tessel.port['GPIO'].pin['G2']);

button1.on('press', function () {
  console.log('Pressing button 1.');
});

button2.on('press', function () {
  console.log('Pressing button 2.');
});

Pressing the different buttons will give you different messages.

Note that I used a breadboard to connect several buttons to the same ground. If you’re interested/want to know more about breadboards, this is a really good place to start.

That’s all! Enjoy.

I’ll keep this tutorial up to date on its projects page

How Tessel Works: The Basics

9/23/2014– Kelsey Breseman

Ever since Jon pushed out the Contribution Guide, I’ve been meaning to distill some of it into a more digestible format. It’s the basics of how Tessel works, hardware and software.

This is an overview, not a complete picture– I recommend that you check out the docs and the full contribution guide if your interest is piqued.

Rolls up sleeves.

Okay, here’s how it works:

Software

Let’s dig into the software first. This software is designed to work on Tessel’s specific hardware, but we’re working on making it portable to other platforms as well.

The basic interaction with Tessel is this:

  1. In the command line, you enter tessel run <file.js>.
  2. From here, the CLI bundles all of the files except those blacklisted in the hardware section of your package.json. If there is no package.json or node_modules folder, Tessel will bundle only the specified file.
  3. We then pass all the files found through Colony, our JS to Lua compiler.The CLI creates a tarball and sends it off to Tessel’s firmware via USB.
  4. The firmware receives the tarball, puts it in RAM*, and loads the script into the Lua VM in Tessel runtime. *or Flash, if you use tessel push instead of tessel run. We’ll go into that in the hardware section.
  5. The runtime environment takes over and defines all the global functions and node modules that the Lua code called into.
  6. When hardware-specific tasks are called by the Lua code, runtime makes calls into the appropriate C functions.
  7. When the process completes, runtime is shut down and the script is freed from memory.
  8. After the initial script runs and sets up event callbacks, the runtime waits for events. When an event occurs, the processor wakes up, runs the callback, and then goes back to sleep.
  9. When no event sources are waiting for events, or when you call process.exit(), runtime is shut down.

To separate this out by components instead of chronology, there are four basic parts of Tessel’s software:

CLI: Command line interface for interacting with Tessel over USB (repo: https://github.com/tessel/cli)

Colony: JavaScript to Lua compiler (bundle installed with the CLI) (repo: https://github.com/tessel/colony-compiler)

Runtime: Lua VM running the interpreted code. The runtime layer also includes the compatibility layer for core JS functions (such as String and Number) and core Node function (such as fs and buffers). (repo: https://github.com/tessel/runtime)

Firmware: C code interfacing the Lua runtime with all of the hardware components (Wifi, RAM, Flash, SPI/UART/I2C busses). The firmware layer also handles interrupts. (repo: https://github.com/tessel/firmware)

All right, that’s the software basics. There are more details overall and for each subsystem on our contribution guide (https://github.com/tessel/contribution-guide), so for the sake of brevity I’ll let you investigate on your own. Let’s move on to Tessel’s hardware.

Hardware

At its core, Tessel runs a 180MHz ARM Cortex-M3 LPC1830. The M3 was chosen as the smallest available chip with the capacity to support external Flash and RAM. Tessel’s Wifi chip is the TI CC3000. There was a lot of excitement about this chip at the time of prototyping, and it was chosen as a good balance between cheap and easy to integrate into a system.

Since Tessel was designed to be intuitive and familiar to web programmers, we needed a bit more memory to play around with than, say, an Arduino. So we have 32 Megabytes each of Flash and SDRAM. (For comparison, Arduino Uno has 32 Kilobytes of Flash, and 2 Kilobytes of SRAM.)

Tessel’s firmware and runtime (compiled into the firmware) are stored in Flash memory. Current firmware takes up about 1.3MB, but the boot and firmware partitions reserve 2MB of memory just in case– leaving you 30MB to use for your own files.

Tessel’s CLI gives you the option to either push or run any given JS file. When you run, code is temporarily stored in RAM and is not persistent across hardware resets; if Tessel loses power, you will need to re-run the code. This is designed for quickly testing code in development.

If you push, the files are saved to Flash memory and run every time Tessel boots up– so if you want to plug Tessel into a battery, you’ll need to tessel push, disconnect, and plug the battery in. This is designed for deployment. You can read more about push vs. run here.

The primary interaction for Tessel takes place through the four module ports. Each can be used to communicate with devices using SPI, I2C, and/or three digital GPIO pins. Ports A, B, and D also include UART, another communication interface.

Module ports are designed for hardware modularity; currently we have fourteen single-function modules (BLE, servo, accelerometer, etc.) that you can swap into (almost) any of these ports. Drivers and APIs are npm installed with the package name written on the silk screen on the module. These modules are also all OSS/OSHW. You can find third-party design guidelines and module design philosophy here.

There’s also a GPIO bank on the board designed to make it easy to interface with other hardware, or anything not available in module form. All of Tessel’s input and output signaling is 3.3V maximum voltage.

You can power Tessel through its microUSB port (5V USB sources only), or through a pair of solderable pins on the board. Please read the guide on powering Tessel before you use these, though.

You can find links to all of Tessel’s hardware designs (schematics and layouts for Tessel and all modules) here: https://github.com/tessel/hardware

Whew! Now that you understand everything about Tessel, you’re all set to contribute to this open source project!

See you on the repos,
Kelsey

Twilio, Tessel, and the Internet of People

9/16/2014– Jon McKay

Twilio and Tessel

Twilio is a company that is near and dear to our hearts at Technical Machine. We’re excited to announce that their Node.js library runs on Tessel. Twilio is the SMS and Voice glue for any communications-based applications and they have an amazing developer experience. Hands down, Twilio is the easiest way to send SMS and voice communications and I’ve yet to meet a dissatisfied customer.

In my opinion, Twilio and Tessel seem like a perfect match. Tessel is the fastest way to gather data about the physical world, and Twilio is the fastest way to get that information to the people who care.

Why SMS?

There are a whole slew of ways devices communicate with each other and with people: lightweight, data transfer protocols (MQTT, CoAP, XMPP, BLE), haptics, or visual displays. But what happens when an individual needs to be notified of an event regardless of where they are in the world?

SMS is the best way to immediately get data to to the right person. While push notifications are also a reliable way of getting information directly to a user, it still requires them to download yet another app. As more and more connected devices have their own applications, it becomes increasingly tedious to download and use a separate smartphone application for each. Text messages are still the simplest way to get data from a device to a smartphone.

Running Twilio on Tessel

When we shipped Tessel, the runtime wasn’t compatible enough with Node for the Twilio Node.js library to run on Tessel. Not only that, but our WiFi state machine was unstable and prone to crashing making HTTP requests unreliable.

We’re really proud of the progress we’ve made since then to get the Twilio Node.js library running directly on a microcontroller. We’ve slogged through a whole slew of WiFi, JavaScript, and Node compatibility bugs for this library to start working. We’re starting to see other libraries (like Keen.io and MQTT which we’ll talk about more soon) Just Work on Tessel and it’s really exciting to see our original design finally coming to fruition.

We worked Ricky Robinett, a developer evangelist at Twilio to test out the Node library as we were fixing it. He was able to write a simple app on Tessel to get an idea of exactly how lazy his dog, Gif, really is. Using the Twilio Node library and the accelerometer module, he could detect when his dog was napping on the job, and send him a text with the nap duration. While it is an, admittedly, silly use case, his blog post shows the basics of loading the Twilio node module, monitoring the accelerometer values, and posting an SMS with an event has occurred. Check it out if you’re interested in sending a text message from Tessel!

Note: SMS in production

Lastly, running Twilio on Tessel is the fastest way to prototype an SMS-enabled system but you would want a different system design when moving to production. For example, you could move to a proxy-service oriented architecture: Tessel would send an HTTP request to a remote server and that server would take care of interacting with the Twilio service. The proxy server could also route incoming SMS messages down to the Tessel.

If you’re building an SMS-enabled Tessel application and you’d like help, feel free to post on our forums or shoot me an email at jon@technical.io.

-Jon

We’re hiring, cool projects, and meeting up

9/15/2014– Updates

We’re hiring

We miss our summer interns– seven people is too few for our grand plans! Check out tessel.io/jobs if you think you can help fill the hole in our hearts.

Progress report

Here’s what we’ve been up to lately: * Bug fixes and feature requests, as always. See the changelogs here. * Prep for conference/hackathon season: there should be Tessel hardware to borrow at most of Major League Hacking’s hackathons, and we’re speaking and providing hardware at a number of to-be-announced conferences. * Improved internal testing infrastructure: we’re working on a continuous integration server that automatically runs a suite of tests on every PR through Tessel and merges if acceptable. * Added contribution labels to Github issues to make it easier to contribute– see details here. * Added Tessel Packs to the store: bundles of modules for specific applications, such as the Hackathon Pack. * Reached out to a lot of customers for feedback– we love to hear your feedback, so much so that Jon spent a lot of time last week individually emailing customers to hear their thoughts. If you have anything to share, please let us know! * Made a meetup group in the Bay Area and held our first couple of events. * Got LuaJIT running some JS scripts.

Meeting up

Hardware is more fun in person– want to start a meetup group in your area at the intersection of hardware and web development? Reach out to kelsey@technical.io for support and ideas– and we’ll cover your meetup fees. Check out our group as an example.

Projects

We’ve been watching projects roll in, as well. Here are a few picks: * Tessel + Auth0 authentication * Neopixel animation over websockets * A ring level using accelerometer + Neopixels * A Meteor.js temperature monitoring dashboard

Do you have a Tessel project you’ve been working on? Please post!

Until next time,
Kelsey, Tim, Ken, Eric, Jon, Jia, and Kevin

An Interview with Stefan van Dockum

8/30/2014– Kelsey Breseman

Stefan Van Dockum, or stefanvandockum on our projects page, has made a number of cool projects lately: a haptic metronome, a bulls-eye level using Neopixels and an accelerometer, Tessel adaptations for a Wii Nunchuck and an NES controller, and a couple of other promising works in progress. So I sent him a message to see if I could learn more about his background, inspirations, and impressions.

Stefan made time to speak with me late at night his time in The Netherlands . He’d just put his two young kids to bed, and so Skyped me quietly, white earbuds in. Quick to smile, he was full of ideas– both for projects he wanted to make and for directions he thought we as a company might want to look.

Kelsey: You’ve made a broad range of projects– what’s your background in engineering?

Stefan: I have a pretty standard background for here in Holland for engineering. I got a bachelor’s degree in higher informatics; embedded systems. Before that I was in electrical engineering.

I hadn’t done anything with engineering until now, since then; I went right into the internet business– that’s more .NET and PHP programming.

I had played with electronics since I was seven, since we got our first Nintendo 8-bit thing, and after that, we got our first XT8086 computer with less than 64 kilobytes of RAM. So I started programming then. But then after that, you get to puberty, so you go skating, guitar playing, drinking, that sort of stuff.

I’m more of a “knower” than a “doer”; if I see something for electronics, I know what it does, but I don’t know exactly how to make it from scratch. So copy and enhance is the standard tactic.

That’s why I love the Tessel right now. It has the electronics– what I went to school for– and it has the programming language that I’ve done the last couple of years, for the internet business. It’s the perfect combination for me right now.

When Tessel came out, I ordered the whole set, and I was very happy.

Kelsey: Would you consider yourself primarily a JavaScript programmer?

Stefan: JavaScript was always a thing you did ‘on the side’. It was not a main thing for me; I was mainly a backend developer. Databases were my specialty. But the last two, three years I’ve gone into JavaScript some more, with JQuery and stuff. Last year, at our work, Node.JS was a hot topic, so we’ve learned stuff from that, too.

In the end, the programming language itself is not that interesting to me; it’s just what you can do with it. I have learned ten programming languages, I think: Delphi, PHP, .NET, Turbo Pascal and even Basic in the old days; I also did some Java stuff in school. I’ve seen almost every programming language there is. The only thing that’s hard is switching between the languages.

Kelsey: Did you have anything particular in mind when you bought a Tessel?

Stefan: Not really; I always had my eye on the Arduino, but the problem was that it was C, and I didn’t want to go back to C after programming with .NET and PHP for so long.

I wanted an Arduino for just making things. You always want to build a robot or something– standard stuff. Just dabbling in electronics is always a cool thing to do. I just wanted to have it as a new gadget.

Kelsey: You’ve been prolific so far; you’ve published, I think, five projects?

Stefan: Five or so. I’ve got some more in my mind.

I need to move to a new house, so I’m thinking about a home sensor network, with small temperature sensors, to monitor the whole house.

I have a checklist of all the modules that work with Tessel. When I got the Tessel first, I said, let’s try module 1. Okay, example code works. What to do with it? Thinking, thinking, don’t know yet, let’s try module 2. Let’s try that one. At first I tried all the example codes. Then you have a really nice idea of what you can do with them.

One thing on my checklist was the infrared module. Controlling your TV is so dull, it’s standard, so controlling the TV was not very cool. But I’m also a portrait photographer. I had my DSLR in front of me, and I was thinking, wait a second, I’ve got a remote for that, and that remote is infrared. I’ve done a couple of product photography assignments; now I can automate my product photography just by sending IR codes to the camera and using the servo to turn a table.

I’m still working on the woodwork part. I went to Ikea to buy some really cheap turntable thing; it’s like seven euros for a turntable, and I just have to put on the servo to move it. That’s a project that I’m still doing. Like I said, moving into a new house, but it will probably be done before the end of the month.

Editor’s note: here is Stefan’s product photography project writeup so far.

Kelsey: A lot of your projects involve a physical component– is that a fun piece of the project for you?

Stefan: It depends on what I want to achieve, the problem is that it takes some more thinking; programming is easier than making a piece of hardware. But it’s bringing back childhood memories, the electrical part. It was fifteen years ago that I created my own PCB boards. In the old days, I etched my own PCB boards, with the lighting and the different kinds of chemicals. When I was at school, the SMD technology was just arriving. I really had to do everything by hand then.

I had an internship that shipped amplifiers to Hong Kong. I was soldering on my own, I made some mistakes, and I really hated that part. But now when I’m tinkering, I’m thinking, why that capacitor, why that resistor?

That’s really a fun part to think of: what kind of schematic do you need? But it’s still a hard part. I think most software programmers really hate that part, to get that electronic stuff up and running. You really don’t know what’s happening if you’ve never had any background. Why would I learn four years for it, if someone could do it in two weeks? So the pre-made modules are pretty cool, because you can just plug in and do your stuff.

Kelsey: How long does it take you to make a project?

Stefan: One evening, or two or three evenings, depending on how much I need to debug.

I’m always thinking about really short code blocks, trying to get those basic blocks first: turn a servo, send an IR command, that sort of stuff. Later on, I can always extend those basic building blocks.

Mostly it’s just one evening to get the prototype running. If I wanted to make it really complete, I think I would be doing two days or something. For the projects that I do right now, I get the idea in the morning, and then in the evening I program it, hook it up, and it’s ready to go.

Kelsey: What are you excited about making right now?

Stefan: The Neopixel stuff is really cool. You can get a nice ring with colorful LEDs. It’s just so easy to program, you can do basically anything with it.

I got a 3D printer, also. I’m trying to mix and match some ideas that I have with the Tessel. But the problem is, my 3D modeling capabilities are also from ten years ago, so I need to pick that up also.

I saw the Rapiro robot– that’s a pretty nice robot for 3D printing. So I want to make it with much more stuff on it– more lights, more talking back.

Robots are pretty standard. You always want to make a robot, but in the end it’s sometimes too hard, and everybody does it. But to make a really cool robot, that’s still on the bucket list.

Kelsey: Have you thought about turning any of your projects into products?

Stefan: I was thinking about how to do it. You need to do it in quantity.

For most people, the Tessel is expensive. It’s not a really expensive thing, but it’s still an expensive thing to buy for a product.

You could do something Bluetooth Low Energy and NFC. I was thinking about a teddy bear with NFC in it. My kids could put the telephone to its paw and an app would come to life and it would say how old the teddy bear is, its birthday, that sort of thing.

It’s in my mind to try selling some things. But the Tessel right now isn’t the right thing to do to sell. You really need to make your own microcontroller with its own chips. I could maybe make things for friends.

Kelsey: What would make it better for the applications you have in mind?

Stefan: The Arduino proto-mini is ten euros if I get it from Hong Kong. But I really hate Arduino’s programming language, and I really like Tessel. You should make a Tessel mini, or some ‘satellite’ sensor like boards which can directly talk to a tessel ‘hub’.

The sensors need wireless communication– I want to make a low-mesh network.

Tessel mini should be one of the products you should sell. Max of two modules, and half its price, you would sell a lot more I think. Especially for hackathons. At my company, there are some other front-end developers who are looking into Tessels, but don’t have the money yet. Sell them by tens, you can really have a cool hackathon.

Kelsey: What do you think is a good direction for this sort of technology?

Stefan: The nicest things about Tessel– and those were the first things that triggered me– there are two things. The JavaScript, and the built-in Wifi.

Connecting a physical thing to the internet is the way to go. The only thing you need to know is, what do you want to do with this connection? It’s an in between medium; you’ve got some actuators, you’ve got some sensors, and you can always reach and trigger them. You can move something through the internet. But in the end, I don’t really have a concrete idea yet. First get the basics up and running and expand from there…

The basic implementation would be the sensors: getting to know your environment, and adapt your environment to the situation. So the the next best thing, what I think, in the next five years is really automating your house and making sure everything in it knows what it’s doing: close the windows, sun screens, temperature, air conditioning. Together with information (weather for example), shared algorithms as API etc.

The other thing I was thinking about is portable stuff. That’s a race against the phone, because your phone can do a lot of things, but they’re consumer things. You can’t add really other hardware things to it, other than the microUSB port. You have Bluetooth protocol. In ten years, maybe there will be a difference between a phone and a microcontroller, but maybe not. That’s a possibility.

Paige’s Intern Farewell

8/29/2014– Paige Cote

Choosing a startup for my first technical internship was pretty scary. While the benefits of working for a very small company are definitely large (I’ll get to that in a minute), I knew that this was going to be jumping into the deep end. Looking back at the end of the summer, I can say that while I was definitely justified in my anxiety, I would make the same choice again.

Jump Right In

The best thing for me about this summer was that I could make an impact from day one. While my other friends shared stories about weeklong onboarding processes and intern projects that would never see the light of day, I was immediately pulled into the craziness of shipping Technical Machine’s first product, with all hands needed. Any worry that I would not be making a significant impact this summer was quickly put behind me. We were working on bug fixes from the first day, and as soon as our customers had Tessels in their hands, we were the first line of support.

After the first few weeks, which included surviving shipping, things hardly slowed down. I eventually got involved with every facet of the company. From web development to firmware to support, I was encouraged to find projects that were interesting to me and tackle them. Because Technical Machine is so small (7 full-time and 3 interns), there were always projects that were genuinely important. I could simply express interest in working a specific project and then start working.

This freedom encouraged me to attempt to solve problems that would have intimidated me a month earlier. It also highlighted a huge benefit of startups. At Technical Machine, everyone who made the product is in the same room/building as you. As I worked to solve problems, I knew I would have the support from the team if I needed it. If something strange was going on with the my project, I could just ask the person who wrote the entire section of code or designed the circuit that you’re having trouble with. It was a pretty awesome introduction to a professional engineering environment.

Back to The Real World

As I get ready to go back to school again this fall, I am so excited to apply what I’ve learned this summer. There are the obvious skills that I gained, like my confidence with JavaScript and general appreciation for writing tests. And then there is the less obvious personal motivation that I will take away from my summer at Technical Machine.

Considering that Tessel didn’t even exist as a concept until about a year ago, the amount of quality product that the team has been able to produce is amazing. I am so close to being in a similar position, and it is incredibly encouraging to see how much I could do with the knowledge I gain in the next few years.

Contributing to Tessel this summer gave me a new perspective to take back to school with me this fall. It gave me insight on what problems I look forward to solving, and what I need to focus on improving if I want to make an impact on similar projects in the future. Working in the startup space feels like the best parts of school mashed into one, there are always new things to learn, and you learn new skills with the purpose of immediately applying it.

This fall you’ll find me back at Olin taking classes, Tessel-vangelizing at medical hackathons in Boston, and trying to learn C on the side so that I can more successfully tackle firmware problems next time I’m presented with that opportunity.

If you have any questions about my summer, feel free to get in touch!

Paige

How to Expose a C Function up to JS Userspace on Tessel

8/27/2014– Jia Huang

This document will be kept up to date on Github

This tutorial goes over how to expose a C function to JS where the user can interact with it via any JS function.

The function will pass this simple test case:

var tessel = require('tessel');
console.log("Can Tessel add?", 3 == tessel.add(1, 2));
  1. Clone down the tessel/firmware repo.
  2. Set up the firmware according to the tessel/firmware readme.
  3. Open up src/tessel.c. Add these lines

    uint32_t tessel_add(uint32_t x, uint32_t y)
    {
        return x + y;
    }
    
  4. Add this function to the header file. Open up src/tessel.h and add

    uint32_t tessel_add(uint32_t x, uint32_t y);
    
  5. Add the Lua binding. Open up src/hw/l_hw.c and add

    static int l_hw_add(lua_State* L)
    {
        uint32_t x = (uint32_t)lua_tonumber(L, ARG1);
        uint32_t y = (uint32_t)lua_tonumber(L, ARG1+1);
        lua_pushnumber(L, tessel_add(x, y));
        return 1; // return 0 if the c function doesn't return a value
     }
     
  6. Scroll down to the bottom of src/hw/l_hw.c where we’re defining all the JS function names in luaL_reg regs[] and add in the following entry:

    {"add", l_hw_add}
    

    So it should look something like:

    luaL_reg regs[] = {
        {"add", l_hw_add},
        // spi
        { "spi_initialize", l_hw_spi_initialize },
        { "spi_enable", l_hw_spi_enable },
        ...
    
  7. Add the JS bindings. Open up builtin/tessel.js and find this function:

    this.deviceId = function(){
        return hw.device_id();
    }; 
    

    Add the following right below it

    this.add = function(x, y){ // the "this" object is referring to the "tessel" object
        return hw.add(x, y); // the "add" function here corresponds with the string in the lua binding. That's how we get from C -> Lua -> JS
    }
    
  8. Go back to the main directory of the firmware repo and do a make arm. You should see an output like this

    [183/183] STAMP obj/tessel-firmware.actions_depends.stamp
    arm-none-eabi-size out/Release/tessel-firmware.elf out/Release/tessel-boot.elf out/Release/tessel-otp.elf
    text       data     bss     dec     hex filename
    824912     3576   24660  853148   d049c out/Release/tessel-firmware.elf
    30848      2260    3232   36340    8df4 out/Release/tessel-boot.elf
    6100      34272      36   40408    9dd8 out/Release/tessel-otp.elf
    

    This outputs the elf file for hardware debugging.

  9. Now go to out/Release/ and do an ls. You should see the following

    build.ninja              tessel-cc3k-patch.bin    tessel-firmware.bin.cpgz
    gen                      tessel-cc3k-patch.elf    tessel-firmware.elf
    obj                      tessel-erase.bin         tessel-firmware.hex
    tessel-boot.bin          tessel-erase.elf         tessel-otp.bin
    tessel-boot.elf          tessel-firmware.bin      tessel-otp.elf
    

    Here’s what each of those do:

    • tessel-boot: bootloader for Tessel. Also writes the Tessel version number (04) in otp.
    • tessel-cc3k-patch: updates the firmware for the CC3000 wifi chip on Tessel. Current version is 1.28.
    • tessel-erase: erases all JS user code on Tessel.
    • tessel-firmware: the firmware for Tessel. This was just changed this to add the ‘.add’ function.
  10. Overwrite the Tessel firmware with the new firmware you just built. In the Release directory:

    tessel update ./tessel-firmware.bin Don’t forget that ./ before tessel-firmware. It specifies a local path. Otherwise tessel update will look for firmware patches on our build server.

  11. Now run the test code you have for this function and it should pass.

If you want to revert back to the original Tessel firmware, just run a tessel update --force which will force Tessel to update to the newest release version.

This document will be kept up to date on Github

Arduino <-> Tessel communication

8/21/2014– Jia Huang

This document will be kept up to date on Github

This is a tutorial for how to pass data back and forth between an Arduino and a Tessel.

The data is passed via a UART bridge. Arduino has the SoftwareSerial library for UART comm and Tessel has it’s built in UART functions.

UART works through having TX (transmit) and RX (recieve) pins. A TX of one device is hooked up to the RX of another device like this:

  • Tessel TX Arduino RX
  • Tessel RX Arduino TX
  • Tessel GND Arduino GND

Step 1: Get an Arduino

The Arduino needs to operate at 3.3V. Some boards which operate at this voltage are:

Both the Seeeduino and the Crowduino can switch between 5V and 3.3V.

Arduino Uno

Arduino Unos send over signals at 5V and this will damage Tessel. If you are planning on using an Arduino Uno, you need to make a 5V to 3.3V level converter which shifts the 5V UART TX signal from the Arduino to 3.3V.

The UART TX coming from Tessel is at max 3.3V, but this will register as a digital “high” signal so it does not need to be boosted up to 5V.

Step 2: Hook up the Arduino to the Tessel

There are 3 pins that need to be hooked up, UART TX, UART RX, and Ground.

In the code example, we’re going to be using Arduino’s SoftwareSerial on pins 10 and 11.

wiring an arduino to a tessel

  • Arduino Pin 10 (orange wire) Tessel Port D, pin TX/G1
  • Arduino Pin 11 (white wire) Tessel Port D, pin RX/G2
  • Arduino Ground (brown wire) Tessel Ground

Step 3: Program the Arduino

Run this code on the Arduino

#include 
#define rxPin 10 // connect to TX of other device
#define txPin 11 // connect to RX of other device

SoftwareSerial tesselBridge =  SoftwareSerial(rxPin, txPin);

void setup()  
{
  // open serial port at 9600 baud
  Serial.begin(9600);
  Serial.println("Starting up...");
  
  // set the data rate for the SoftwareSerial port
  tesselBridge.begin(9600);
}

void loop() // run over and over
{
  if (tesselBridge.available())
    Serial.write(tesselBridge.read());
  if (Serial.available())
    tesselBridge.write(Serial.read());
}

Step 4: Program Tessel

Make a folder for the code:

mkdir arduinoBridge;
cd arduinoBridge; touch uart.js;

Put this in the uart.js file.

var tessel = require('tessel');
var led1 = tessel.led[0].output(0);
var led2 = tessel.led[1].output(0);
var i = 0;

// baudrate must match the baudrate set in the Arduino file
uartBridge = tessel.port['D'].UART({baudrate: 9600}); 

uartBridge.on('data', function(data){
  // UART data is not packetized, so you will get the data 
  // buffer as the message is sent. This means that long
  // messages will be truncated as several events.
  
  var number = parseInt(data[0]) - 48; // convert hex to ascii to int
  console.log("got data", data, number);

  if (number == 1)
    led1.toggle();

  if (number == 2)
    led2.toggle();
});

// every 3 seconds write some data over to the arduino
setInterval(function(){
  uartBridge.write("Hi there "+i+"\n");
  i++;
}, 3000);

Run the code with tessel run uart.js, or if you want this to be persistent through power cycles, tessel push uart.js.

Step 5: Test it

You should be able to go into the Arduino console and see the blue and green LEDs on Tessel change as you enter a “1” or a “2”.

terminal

This document will be kept up to date on Github

Tessel Faster Better Stronger

8/20/2014– Nathan Lintz

How do we make Tessel faster? How do we keep Tessel simple for users yet powerful enough to take on big problems? What does it take to make a bulletproof wifi connected microcontroller that can truly deliver on the promise of the Internet of Things? These were just a few of the questions which guided the projects I worked on the summer.

To solve these sorts of problems, I focused on improving the speed of Tessel by writing new firmware apis and porting the Tessel platform to other chipsets. I learned a lot about developing hardware and software platforms, so I thought I’d share some of the insights I gained along the way.


How Fast? This Fast

Moving Pixels

I was inspired to work on improving the Tessel’s performance after reading a request on our forums for an LCD screen module. I naively believed that getting the Tessel to cooperate with a screen would be as simple as porting a C graphics library to JavaScript and plugging in an LCD.

My first attempt resulted in a graphics library which could output approximately 1 pixel a second. At this rate, filing a phone screen sized display would take approximately 100 hours…bummer. I profiled the program to find what was taking so long and it turned out that making a JavaScript call per pixel was causing the library’s performance to degrade dramatically.

Not wanting to give up quite yet, I decided to dive into the firmware and see if there was any way to pump out pixels at a faster rate. I created a new hardware API for the Tessel, the SPI Batch API, which improved the performance of the graphics library I wrote by a factor of 400! With this new implementation we went from making one JS call per pixel to one JS call for the entire screen. When I tested the library, colorful pixels began pouring into the screen, proving that graphics programming is possible on the Tessel.

Developing a graphics library and a firmware API for the Tessel taught me a lot about the power and limitations of JavaScript. When it comes to event driven programming and IO bound tasks, JavaScript is great. However, when it comes to matters of raw speed, C is usually the right answer. This insight can be distilled into the following heuristic which is applicable any time you’re writing code which involves hardware and software components:

For CPU bound tasks, like pushing pixels to a buffer,write your code in C. For IO bound tasks, like reading from a file or handling HTTP requests, use a high level language like JavaScript.

Portable Tessel - Modules Everywhere

After modifying the Tessel firmware to handle graphics, I talked to the team about other ways we could improve Tessel’s performance. We realized that many of our problems could be solved by having an operating system. At the moment, Tessel doesn’t run an operating system; rather, it has a firmware layer which can run a single program. As a result, we can’t use libraries which rely on an OS. By running Tessel on a Linux board, we would have access to these sorts of libraries such as V8, Google’s JS engine, and the Linux TCP stack. This insight blossomed into the Portable Tessel Platform, a node package which emulates the Tessel API on a computer such as the Raspberry Pi or Cubieboard.


Raspberry Pi

Cubieboard

I started off this project by writing up a spec and picking node libraries that would emulate the hardware APIs for the Tessel. Our modules each use either SPI, UART, GPIO pins, I2C, or some combination thereof. After some quick searching on NPM, I found found libraries which would implement the needed protocols.

The libraries I found seemed to work, so I assumed that all I had to do was wire the boards to the modules. Unfortunately, I neglected to make sure that the hardware of the different boards was similar enough to the Tessel and that Linux fully supported all of the drivers I needed. I began testing some of our modules on the Raspberry Pi and Cubieboard, and I found that I2C on the Raspberry Pi has issues communicating with our modules, as its processor doesn’t support certain commands such as repeated start transfers. Similarly, the Cubieboard doesn’t have SPI support unless you recompile the kernel drivers.

After discovering that the boards did not support the needed protocols, I began to research how other people got them working. It took a while, but eventually I found a way to properly compile the drivers for the Cubieboard and how to fix the I2C driver for Raspberry Pi. Once I had working drivers, I just had to hook up the boards to the Tessel modules and the Portable Tessel Platform was born. Now users can build projects using our hardware modules on their own boards, opening our platform up to people who haven’t purchased a Tessel yet.

Working on the Portable Tessel Platform taught me a lot about the challenges of hardware-software integration. In pure software projects, it is easy to just swap out or modify source code to meet your needs. In hardware, planning out everything ahead is necessary as some boards not have all the features you need. I was lucky that I found new drivers for the Cubieboard and Raspberry Pi, but picking boards which have full support for SPI and I2C would have made building the Portable Tessel Platform much easier.

Next year I’ll be back at college so you won’t be hearing from me on the blog for a while. Please message me @nlintz if you get a chance to build any exciting hardware projects on the Portable Tessel Platform or graphics projects using SPI Batch.

Best,
Nathan Lintz