How a Johnny-Five program works

In this section, we'll take a look at the internals of a Johnny-Five program in more detail, so we can start building more complex applications.

Objects, functions, and events

Johnny-Five programs work using an event-based structure, and there are three concepts to keep in mind: objects, functions, and events.

Objects tend to programmatically represent our physical electronic components and are usually constructed using the new keyword. A few examples of objects in Johnny-Five include the five object, which represents the Johnny-Five library, the Board object, which represents our microcontroller; and the LED object, which will programmatically represent our LED:

var led = new five.Led(11);

Functions are available for the objects we create and usually represent the actions that our robots can do. For instance, the LED object has an on() and off() function that turns the LED on and off:

led.on();
led.off();
led.blink();
led.stop();

Events are fired on objects and represent observable points in our program. For example, the Board object fires a ready event when the board is ready to receive instructions from a Johnny-Five program.

We can also set events on a pin to track events on our LED:

var myPin = new five.Pin(11);
myPin.on('high', function(){
  console.log('pin 11 set to high!'),
});

We will use all three of these concepts in every Johnny-Five program we write, so it's good to normalize our vocabulary early!

Going over our blink-LED script

In the previous chapter, we wrote a small script to blink an on-board LED on and off. Let's take a look at this code in detail and outline the objects, functions, and events we have used:

var five = require("johnny-five");

The preceding line just pulls johnny-five into our program so that we can use it.

var board = new five.Board();

The preceding line constructs our board object. Note that, without parameters, Johnny-Five assumes you are using an Arduino and guesses the serial port for you.

board.on("ready", function() {
  var led = new five.Led(13);
  led.blink(500);
});

Here, we set up a listener on our Board object for the ready event. When the board is ready, our handler instantiates an Led object at pin 13 and makes the LED blink by calling the blink function on that object.

This will be the basic format for most Johnny-Five functions: create a Board object, create a listener and handler for the ready event, and then, within the ready event handler, create component objects and call functions through them. We can also add listeners and handlers to the component objects—we'll talk about this in the next few chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.105.108