Skip to content

4. Making the Bot Move

Kevin Leung edited this page Jul 29, 2017 · 5 revisions

Congrats! You are now at the part where we can really have some fun !

  1. First is to make sure you have the proper node modules (if you followed past steps you should already have these installed).

npm install -g johnny-five

npm install -g particle-io

  1. Create a file in your working directory named app.js

  2. Import your node modules into the code and setup up your Photon

var five = require("johnny-five");
var Particle = require("particle-io");

var board = new five.Board({
  io: new Particle({
    token: '4454731742f262fcb07e21106219cf024c7f5743',
    deviceName: 'GabbyPhoton'
  })
});
  1. Create your right wheel and left wheel objects once you are connected to your board, and set the speed.
board.on("ready", function() {
  console.log('ready');

  var rightWheel = new five.Motor({
    pins: { pwm: "D0", dir: "D4" },
    invertPWM: true
  });

  var leftWheel = new five.Motor({
    pins: { pwm: "D1", dir: "D5" },
    invertPWM: true
  });

  var speed = 255;

});
  1. Following the speed, you want to include the functions for direction, using the definitions Johnny Five has for the left and right wheels. We will also add an exit function, for exiting the application.
  function reverse() {
    leftWheel.rev(speed);
    rightWheel.rev(speed);
  }

  function forward() {
    leftWheel.fwd(speed);
    rightWheel.fwd(speed);
  }

  function stop() {
    leftWheel.stop();
    rightWheel.stop();
  }

  function left() {
    leftWheel.rev(speed);
    rightWheel.fwd(speed);
  }

  function right() {
    leftWheel.fwd(speed);
    rightWheel.rev(speed);
  }

  function exit() {
    leftWheel.rev(0);
    rightWheel.rev(0);
    setTimeout(process.exit, 1000);
  }
  1. In order to control the device with these functions, we will use the keypad and set a keyMap and accept Standard Input. Insert this code after the exit function.
var keyMap = {
    'up': forward,
    'down': reverse,
    'left': left,
    'right': right,
    'space': stop,
    'q': exit
  };

  var stdin = process.stdin;
  stdin.setRawMode(true);
  stdin.resume();

  stdin.on("keypress", function(chunk, key) {
      if (!key || !keyMap[key.name]) return;      

      keyMap[key.name]();
  });

Full code here

Clone this wiki locally