Skip to content

Instantly share code, notes, and snippets.

@BrianGenisio
Created November 15, 2014 02:10
Show Gist options
  • Save BrianGenisio/ae315650d5dbdeba996e to your computer and use it in GitHub Desktop.
Save BrianGenisio/ae315650d5dbdeba996e to your computer and use it in GitHub Desktop.
Line following robot using IR.Reflect.Array
// Video: http://youtu.be/i6n4CwqQer0
var fs = require("fs"),
five = require("johnny-five"),
ReflectArray = require("./reflect.array"),
board = new five.Board();
var stdin = process.stdin;
stdin.setRawMode(true);
stdin.resume();
var calibrationFile = ".calibration";
var drivingRules = {
0: {
left: { dir: 'cw', speed: 0.01},
right: { dir: 'ccw', speed: 0.07}
},
1000: {
left: { dir: 'cw', speed: 0.02},
right: { dir: 'ccw', speed: 0.05}
},
2000: {
left: { dir: 'cw', speed: 0.04},
right: { dir: 'ccw', speed: 0.05}
},
2500: {
left: { dir: 'cw', speed: 0.05},
right: { dir: 'ccw', speed: 0.05}
},
3000: {
left: { dir: 'cw', speed: 0.05},
right: { dir: 'ccw', speed: 0.04}
},
4000: {
left: { dir: 'cw', speed: 0.05},
right: { dir: 'ccw', speed: 0.02}
},
5001: {
left: { dir: 'cw', speed: 0.07},
right: { dir: 'ccw', speed: 0.01}
}
};
board.on("ready", function() {
var eyes = new five.IR.Reflect.Array({
emitter: 13,
pins: ['A0', 'A1', 'A2', 'A3', 'A4', 'A5'],
freq: 20
});
var wheels = {
left: new five.Servo({ pin: 10, type: "continuous" }),
right: new five.Servo({ pin: 9, type: "continuous" })
};
this.repl.inject({
eyes: eyes,
wheels: wheels
});
function init() {
eyes.enable();
wheels.left.stop();
wheels.right.stop();
calibrate(drive);
}
function calibrate(whenComplete) {
var savedCalibration, calibrating = true;
if(fs.existsSync(calibrationFile)) {
eyes.loadCalibration(JSON.parse(fs.readFileSync(calibrationFile)))
whenComplete();
return;
}
console.log('Calibrating. Press a key...');
eyes.calibrateUntil(function() { return !calibrating; });
stdin.once('keypress', function() {
calibrating = false;
console.log('Done:', eyes.calibration);
fs.writeFile(calibrationFile, JSON.stringify(eyes.calibration));
whenComplete();
});
}
function drive() {
eyes.on('line', function(err, line) {
var rule;
var threshold = Object.keys(drivingRules).find(function(r) {
return line <= parseInt(r);
});
if(!threshold) {
console.log("Could not find threshold for " + line);
}
rule = drivingRules[threshold];
wheels.left[rule.left.dir](rule.left.speed);
wheels.right[rule.right.dir](rule.right.speed);
});
}
init();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment