rchristiani.github.io/torontojs-nodebots
Lead Instructor & Developer at HackerYou
@Rchristiani on Twitter
ryanchristiani.com
letslearnes6.com
http://rchristiani.github.io/torontojs-nodebots/
Starter FilesJohnny Five is a great library for interacting with a board! And it has great documentation, http://johnny-five.io/api/
Before you can get started you have to install a Firmata to the board, this is a protocol used to communicate with the Micro controller. This is already done for you!
But if you do that at home, you need to install the StandardFirmata
Let's connect the boards and write out first program! Open up the simple folder from the startFiles in your text editor.
Navigate to the folder in your terminal and run npm install
const j5 = require('johnny-five');
const board = new j5.Board();
const j5 = require('johnny-five');
const board = new j5.Board();
board.on('ready',function() {
console.log('Beep Boop');
});
Now run node robot.js
, after a little bit we should see Beep Boop
The motors are already set up for you, so there is no wiring required here. They are connected to a driver, this driver allows us to control the server motors(set up to be continuous) forward and backwards.
const motorOne = new j5.Motor({
pins: {
pwm: 3,
dir: 2
},
invertPWM: true
});
Here we can created a new motor and configured it, we need to tell Johnny Five the pins being used, one is the pwm
pin(controls speed) and one is the dir
pin(controls direction).
Setting up a motor is good and all, but how do we test if it works? We can inject our component into a repl!
this.repl.inject({
motorOne
});
Running node robot.js
, will start it back up again, but this time we can interact with the motor!
>> motorOne.start(); //Starts the motor
>> motorOne.stop();
const motorTwo = new j5.Motor({
pins: {
pwm: 5,
dir: 4
},
invertPWM: true
});
this.repl.inject({
motorOne,
motorTwo
});
motorOne.forward(255);
boardTwo.wait(2000,() => {
motor.stop();
});
The motors also emit events. These events follow the names of the methods from above!
start
, stop
, forward
, reverse
. To use these we can follow this pattern.
motor.on('start',() => {
board.wait(2000,() => {
motor.stop();
});
});
npm install -g nodemon
Real time communication.
Since we are writing JS on the board, we can use all the node packages we might be familiar with. In this case socket.io is going to be one to look at!
With socket.io we can create a real time connection between out bot a server and however many clients we want.
Provided for you are a few starterFiles for the a socket.io, let's review them now!