Johnny-Five 双舵机驱动实战:用连续旋转舵机搭建简易双轮小车
Johnny-Five 双舵机驱动实战:用连续旋转舵机搭建简易双轮小车
本文基于 johnny-five 官方示例 docs/servo-drive.md 展开,讲解如何用两块连续旋转舵机(Continuous Rotation Servo)在 Arduino 上搭建一个可前进、可停车的双轮驱动小车。读完本文,你将掌握连续舵机与标准舵机的区别、Servo 与 Servos 集合的用法,以及 cw() / ccw() / stop() 驱动的底层原理,并能直接运行仓库中现成的示例程序。
示例目标:两根 PWM 引脚驱动两个“轮子”
docs/servo-drive.md 的核心是一段非常精简的机器人驱动代码:把两块连续旋转舵机分别接到 Arduino 的 9、10 号引脚,把它们当作小车的左右轮,通过 johnny-five 的 Servos 集合同时控制,实现前进 3 秒后自动停止。
##### Servos on pins 9 and 10
Servos connected to pins 9 and 10. Requires servos on pins that support PWM (usually denoted by ~).
引脚要求很明确:必须选择支持 PWM 的引脚,在 Arduino Uno 等开发板上通常以 ~ 符号标注(如 ~9、~10、~11)。因为舵机的角度/转速本质上是由引脚上输出的 PWM 脉冲宽度(微秒级)决定的,普通数字引脚无法产生这一信号。
仓库为该示例提供了配套的接线图与 Fritzing 工程文件:
- 接线图:docs/breadboard/servo-two.png
- Fritzing 源文件:docs/breadboard/servo-two.fzz
运行方式与完整代码
示例位于 eg/servo-drive.js,在命令行中直接运行即可:
node eg/servo-drive.js
说明:
eg/目录下示例使用的是本地源码路径require("../lib/johnny-five.js"),如果你的项目通过 npm 安装了 johnny-five,则按文档写法使用require("johnny-five")。运行前请确保开发板已通过 Firmata 固件连接成功。
完整代码(与文档一致,含注释):
const {Board, Servo, Servos} = require("johnny-five");
const board = new Board();
board.on("ready", () => {
let wheels = {};
// Create two servos as our wheels
wheels.left = new Servo({
pin: 9,
// `type` defaults to standard servo.
// For continuous rotation servos, override the default
// by setting the `type` here
type: "continuous"
});
wheels.right = new Servo({
pin: 10,
// `type` defaults to standard servo.
// For continuous rotation servos, override the default
// by setting the `type` here
type: "continuous",
invert: true // one wheel mounted inverted of the other
});
// reference both together
wheels.both = new Servos([wheels.left, wheels.right]);
wheels.both.stop();
// Add servos to REPL (optional)
board.repl.inject({
wheels
});
// Drive forwards
// Note, cw() vs ccw() might me different for you
// depending on how you mount the servos
wheels.both.cw();
// Stop driving after 3 seconds
board.wait(3000, wheels.both.stop);
});
这段代码包含了几个值得细究的关键点,下面逐一展开。
为什么连续舵机要显式声明 type: "continuous"
Servo 构造器的默认类型是标准舵机,对应源码 lib/servo.js 中的:
this.type = options.type || "standard";
标准舵机(standard servo)只能转动到 0°~180° 之间的指定角度;而连续旋转舵机(continuous rotation servo)本质是一个带反馈的电机,输入脉冲宽度决定的是转速与方向,而不是角度。因此驱动 API 完全不同,文档在代码注释中专门强调:
// `type` defaults to standard servo.
// For continuous rotation servos, override the default
// by setting the `type` here
除此之外,johnny-five 还提供了一个专门的便捷子类 Servo.Continuous(见 lib/servo.js),它内部自动补上 options.type = "continuous":
Servo.Continuous = class extends Servo {
constructor(pinOrOpts) {
const options = {};
if (typeof pinOrOpts === "object") {
Object.assign(options, pinOrOpts);
} else {
options.pin = pinOrOpts;
}
options.type = "continuous";
super(options);
}
};
因此 new Servo({ pin: 9, type: "continuous" }) 与 new Servo.Continuous(9) 等价——示例文档选择了前者以显式展示 type 选项的作用,而 docs/servo-continuous.md 中的键盘控制示例则使用了 Servo.Continuous。
从源码看,还有一个默认行为值得注意:当 type 为 "continuous" 时,构造器在初始化末尾会自动调用一次 this.stop()(见 lib/servo.js),把舵机立即置入停止状态,防止上电即乱转:
if (options.type === "continuous") {
this.stop();
}
这也解释了示例代码中 wheels.both.stop() 的存在意义:显式确保两个轮子都静止后再开始控制。
invert: true:处理反装轮子的方向问题
wheels.right = new Servo({
pin: 10,
type: "continuous",
invert: true // one wheel mounted inverted of the other
});
双轮小车在物理安装时,左右轮往往呈镜像布置(一个舵机头朝左、一个朝右),这会导致同样的 cw() 指令在两轮上产生相反的转向。invert 选项就是为了在软件层面统一方向。
其实现位于 lib/servo.js 与 to() 方法中:
this.invert = options.isInverted || options.invert || false;
在 lib/servo.js,当 invert 为真时,输出角度会在 degreeRange 上做镜像映射:
if (this.invert) {
degrees = Fn.map(
degrees,
this.degreeRange[0], this.degreeRange[1],
this.degreeRange[1], this.degreeRange[0]
);
}
即 0 → 180、180 → 0、90 → 90。这样即使两个舵机物理朝向相反,cw() 仍然能驱动小车整体向前。代码注释中的提示值得牢记:
// Drive forwards
// Note, cw() vs ccw() might me different for you
// depending on how you mount the servos
如果你的两个舵机是同向安装的,则不需要 invert;具体是 cw() 还是 ccw() 前进,取决于安装方式,可能需要实测调换。
用 Servos 集合统一控制左右轮
wheels.both = new Servos([wheels.left, wheels.right]);
Servos 是 johnny-five 的集合(Collection)类,定义在 lib/servo.js,其底层 type 指向 Servo:
class Servos extends Collection {
constructor(numsOrObjects) {
super(numsOrObjects);
}
get type() {
return Servo;
}
}
集合类的核心机制在 lib/mixins/collection.js:构造函数会把传入的对象数组逐个实例化为 Servo,并让集合支持数组式下标访问与迭代。
更重要的是方法转发机制 Collection.installMethodForwarding(见 lib/mixins/collection.js),它会将 Servo.prototype 上的所有方法复制到 Servos.prototype 上,并在调用时逐个转发给集合中的每个成员:
accum[method] = function(...args) {
const length = this.length;
for (let i = 0; i < length; i++) {
this[i]method;
}
return this;
};
在 lib/servo.js 中显式做了安装:
Collection.installMethodForwarding(
Servos.prototype, Servo.prototype, {
skip: [Animation.normalize, Animation.render]
}
);
因此 wheels.both.cw()、wheels.both.stop() 会同时作用于左右两个舵机,不需要分别写两行代码。这也让后续加装更多轮子(如四驱车)时扩展非常方便。
cw / ccw / stop 与死区(deadband)原理
连续舵机的转向控制由 cw()(顺时针)与 ccw()(逆时针)两个 API 承担,其实现位于 lib/servo.js:
["clockWise", "cw", "counterClockwise", "ccw"].forEach(api => {
Servo.prototype[api] = function(rate) {
let range;
rate = rate === undefined ? 1 : rate;
/* istanbul ignore if */
if (this.type !== "continuous") {
this.board.error(
"Servo",
`Servo.prototype.${api} is only available for continuous servos`
);
}
if (api === "cw" || api === "clockWise") {
range = [rate, 0, 1, this.deadband[1] + 1, this.range[1]];
} else {
range = [rate, 0, 1, this.deadband[0] - 1, this.range[0]];
}
return this.to(Fn.scale.apply(null, range) | 0);
};
});
解读这段实现:
rate是 0~1 之间的速度倍率,默认1(全速)。cw(0.5)即半速顺时针。- 实际输出值是角度,再经
to()内部的映射转换为 PWM 微秒写入舵机。默认pwmRange为<a href="https://link.gitcode.com/i/62c6006acd9be1e19288c89913e693cc" target="_blank">600, 2400]、degreeRange为[0, 180](见 [lib/servo.js),因此全速cw()会写入约 2400µs 的脉冲,全速ccw()写入约 600µs。 deadband(死区)默认<a href="https://link.gitcode.com/i/31ae106792f9b4ef701bc5593cbb72ce" target="_blank">90, 90](见 [lib/servo.js),即 90° 对应的 1500µs 附近区域;连续舵机在这个区间内应保持静止。cw()从deadband[1] + 1起步、ccw()从deadband[0] - 1起步,正是为了保证命令确实越过死区、产生实际转动。
stop() 的实现(见 lib/servo.js)则把角度设置回死区中点,使舵机停下:
stop() {
const state = priv.get(this);
if (state.animation) {
state.animation.stop();
}
if (this.type === "continuous") {
this.to(
this.deadband.reduce((a, b) => Math.round((a + b) / 2))
);
} else {
clearInterval(this.interval);
}
return this;
}
这些行为在测试 test/servo.js 中有直接验证:
cw()调用后servoWrite收到2400,ccw()收到600(对应cw/ccw测试用例);- 自定义
deadband: [85, 95]时,cw(0.5)得到角度值138、ccw(0.5)得到42; stop()会把角度置回deadband中点([85, 95]→90,[100, 105]→103);- 对标准舵机调用
cw()/ccw()会抛错(nonContinuousErrors用例)。
此外测试也验证了 rangePlusDeadband 的组合行为:设置 deadband: [85, 95]、range: [20, 160] 后,cw() 写入 2200µs、cw(0.5) 写入 1880µs,说明 range 会进一步限制转速映射区间。
board.wait:3 秒后自动停车
示例最后用 board.wait(3000, wheels.both.stop) 实现延时停车。注意这里传入的是函数引用,3 秒后回调会被触发。
其实现位于 lib/board.js:
Board.prototype.wait = function(time, callback) {
setTimeout(callback, time);
return this;
};
wait() 基于 setTimeout,是 johnny-five 中非常常用的时序原语;与之配套的还有周期执行的 board.loop(time, callback)(见 lib/board.js),可用于让小车循环前进/后退。把两者组合,就可以写出更复杂的巡线、避障等行为逻辑。
运行前置条件与注意事项
- 固件:开发板需烧录 StandardFirmata 等支持 Firmata 协议的固件,johnny-five 才能通过串口控制引脚。查看 docs/board.md 了解开发板连接与固件烧录流程。
- 引脚:必须使用支持 PWM 的引脚(通常带
~标记)。如果在 debug 模式下使用了非 PWM 引脚,Servo构造器会通过Board.Pins.Error报错(见 lib/servo.js)。 - 供电:连续舵机在转动时电流较大,示例中两块舵机同时驱动时,建议使用独立电源为舵机供电,避免与主控共电造成电压跌落复位。
- 方向校准:
cw()/ccw()的实际转动方向取决于舵机品牌与安装方式,文档明确提示可能需要根据你的安装情况调整;invert是左右轮反装时的标准解法。
扩展:从固定时序到交互控制
servo-drive.js 是固定的“前进 3 秒→停止”时序,若想进一步体验连续舵机的交互控制,仓库中的 docs/servo-continuous.md 与 eg/servo-continuous.js 提供了一个基于 keypress 的键盘控制版本:方向键上/下对应 cw()/ccw(),空格对应 stop(),按 q 退出。两者结合即可快速把示例改造成可遥控的小车底盘。
参考文件索引
- 官方示例文档:docs/servo-drive.md
- 可运行示例:eg/servo-drive.js
- 舵机核心实现:lib/servo.js
- 集合方法转发机制:lib/mixins/collection.js
wait/loop时序原语:lib/board.js- 连续舵机测试用例:test/servo.js
- 接线图:docs/breadboard/servo-two.png 与 docs/breadboard/servo-two.fzz
- 键盘控制进阶示例:docs/servo-continuous.md、eg/servo-continuous.js