通过 JavaScript (Johnny-Five) 控制 Ardunio

Johnnt-Five 是一个支持 JavaScript 语言编程的机器人IOT 开发平台,基于 Firmata 协议。
该项目在 Github 上有着很好的活跃度,官网上也有非常详尽的 API 文档和丰富的实例

一、环境搭建

安装 Arduino IDE

安装 Arduino IDE 主要是为了向开发板中刷入 Firmata 程序。Firmata 是计算机软件和微控制器之间的一种通信协议
当开发板中刷入了 Firmata 固件后,电脑端就可以使用同样基于 Firmata 协议的框架对开发板进行编程。

Arduino IDE 可以直接从官网下载对应系统版本的安装包进行安装。
安装完成后进入 文件示例FirmataStandardFirmataPlus ,将该程序刷入 Arduino 开发板即可。

《通过 JavaScript (Johnny-Five) 控制 Ardunio》 arduino IDE

Johnny-Five 框架

Johnny-Five 框架需要电脑系统里安装 Node.js 程序。可以直接从官网下载安装,也可以使用 nvm 等版本管理工具安装需要的版本
nvm 方式可参考版本管理工具(nvm、virtualenv(wrapper) 和 rbenv 的安装与使用)

安装完成后直接在项目目录下运行 npm 命令即可:
$ npm install johnny-five

二、Hello World

在项目目录下创建 blink.js 文件:

var five = require("johnny-five");
var board = new five.Board();

// The board's pins will not be accessible until the board has reported that it is ready
board.on("ready", function() {
  console.log("Ready!");

  // Create a standard `led` component instance
  var led = new five.Led(13);

  // "blink" the led in 500ms
  led.blink(500);
});

使用 node blink.js 命令运行项目,效果如下:

《通过 JavaScript (Johnny-Five) 控制 Ardunio》 blink.js

此时 Arduino 板子上接 13 引脚的红色 LED 开始以 500 毫秒的间隔闪烁,使用
.exit 命令退出 nodejs 的 Repl 后停止闪烁。

REPL

在项目目录下创建 repl.js 文件:

var five = require("johnny-five");
var board = new five.Board();

board.on("ready", function() {
  console.log("Ready event. Repl instance auto-initialized!");

  var led = new five.Led(13);

  this.repl.inject({
    // Allow limited on/off control access to the
    // Led instance from the REPL.
    on: function() {
      led.on();
    },
    off: function() {
      led.off();
    }
  });
});

运行效果如下:

《通过 JavaScript (Johnny-Five) 控制 Ardunio》 Repl

可以在 nodejs 的 Repl 中使用
on()
off() 对 LED13 进行打开和关闭操作。

三、Button

创建 button.js 文件:

var five = require("johnny-five"),
  board, button;

board = new five.Board();

board.on("ready", function() {

  // Create a new `button` hardware instance.
  button = new five.Button(2);

  // Inject the `button` hardware into the Repl instance's context;
  board.repl.inject({
    button: button
  });

  // "down" the button is pressed
  button.on("down", function() {
    console.log("down");
  });

  // "hold" the button is pressed for specified time.
  //        defaults to 500ms (1/2 second)
  button.on("hold", function() {
    console.log("hold");
  });

  // "up" the button is released
  button.on("up", function() {
    console.log("up");
  });
});

线路接法如下:

《通过 JavaScript (Johnny-Five) 控制 Ardunio》 线路图

运行效果:

《通过 JavaScript (Johnny-Five) 控制 Ardunio》 Button

按下并释放按键时 Repl 中输出 downup。按住按键时输出 hold

尬尴,JavaScript 不太熟悉,以后有时间多做尝试。
官方文档真的很详细。。。

点赞