Last active
August 29, 2015 13:58
-
-
Save xat/9978542 to your computer and use it in GitHub Desktop.
An untested node-port of https://github.com/foertel/pihp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Gpio = require('onoff').Gpio, | |
async = require('async'), | |
_ = require('underscore'); | |
var measureDistance = function(opts) { | |
var options = _.defaults(opts, { | |
trigger: 24, | |
echo: 25, | |
leds: [4, 17, 18, 27, 22, 23], | |
timeout: 2000 | |
}), | |
distances = [], | |
triggerGpio, | |
echoGpio, | |
ledsGpio, | |
getDistance = function(cb) { | |
var start, to; | |
var run = function() { | |
to = setTimeout(function() { | |
echoGpio.unwatchAll(); | |
cb(new Error('timeout reached')); | |
}, options.timeout); | |
echoGpio.watch(function(val) { | |
if (val) { | |
start = Date.now(); | |
} else { | |
clearTimeout(to); | |
echoGpio.unwatchAll(); | |
cb(null, (Date.now() - start) * 34300 / 2); | |
} | |
}); | |
}; | |
triggerGpio.write(1, function() { | |
setTimeout(_.partial(_.bind(triggerGpio.write, triggerGpio), 0, run), 1); | |
}); | |
}, | |
getAverageDistance = function() { | |
var len = distances.length; | |
distances.sort(function(a, b) { | |
if (a > b) return 1; | |
if (b > a) return -1; | |
return 0; | |
}); | |
distances = distances.slice(Math.round(len * 0.25), Math.round(len * 0.5)); | |
return _.reduce(distances, function(distance, memo) { | |
return distance + memo; | |
}, 0) / len; | |
}, | |
switchLeds = function() { | |
var ledsToSwitch = Math.floor(getAverageDistance() / 10); | |
_.each(ledsGpio, function(ledGpio, idx) { | |
ledGpio.writeSync(idx < ledsToSwitch ? 1 : 0); | |
}); | |
}; | |
return { | |
start: function() { | |
distances = []; | |
triggerGpio = new Gpio(options.trigger, 'out'); | |
echoGpio = new Gpio(options.echo, 'in'); | |
ledsGpio = _.map(this.options.leds, function(pin) { | |
return new Gpio(pin, 'out'); | |
}); | |
async.forever(function(next) { | |
getDistance(function(err, distance) { | |
if (err) { | |
return next(); | |
} | |
distances.push(distance); | |
if (distances.length > 30) { | |
switchLeds(); | |
} | |
next(); | |
}); | |
}); | |
}, | |
stop: function() { | |
triggerGpio.unexport(); | |
echoGpio.unexport(); | |
_.each(ledsGpio, function(ledGpio) { | |
ledGpio.unexport(); | |
}); | |
} | |
}; | |
}; | |
var dist = measureDistance(); | |
// Boot the whole thing | |
dist.start(); | |
process.on('SIGINT', function() { | |
dist.stop(); | |
process.exit(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment