Skip to content

Instantly share code, notes, and snippets.

@randunel
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randunel/8965541 to your computer and use it in GitHub Desktop.
Save randunel/8965541 to your computer and use it in GitHub Desktop.
espruino-led-dim
var DURATION = 2000;
function sign(num) {
return Math.round(Math.abs(num) / num);
}
function round(num, decimals) {
return (Math.round(num * Math.pow(10, decimals))) / Math.pow(10, decimals);
}
var currentIntensity = 0;
var interval;
var stepInterval;
function dim(intensity, time, steps, cb) {
console.log('run to', intensity);
if (typeof intensity == 'undefined') intensity = 0;
if (typeof time == 'undefined') time = 1000;
if (typeof steps == 'undefined') steps = 100;
var freq = time/steps;
var intensityStep = round((intensity - currentIntensity) / steps, 2);
var signStep = sign(intensityStep);
intensityStep = Math.abs(intensityStep);
if (typeof stepInterval != 'undefined') {
console.log('clearing stepInterval', typeof stepInterval, stepInterval);
clearInterval(stepInterval);
console.log('should have cleared stepInterval', typeof stepInterval, stepInterval);
// Workaround for clear fail
stepInterval = undefined;
}
stepInterval = setInterval(function() {
currentIntensity = currentIntensity + (intensityStep * signStep);
if (sign(intensity - currentIntensity) != signStep) {
console.log('done', currentIntensity);
currentIntensity = currentIntensity - (intensityStep * signStep);
console.log('done', currentIntensity);
clearInterval(stepInterval);
if (typeof cb !== 'undefined') cb();
}
if (typeof interval !== 'undefined') clearInterval(interval);
interval = setInterval(function() {
digitalPulse(LED1, 1, Math.abs(currentIntensity * 10));
}, 10);
}, freq);
}
var self = this;
function callback() {
return dim(Math.round(currentIntensity) === 0 ? 1 : 0, DURATION, 100, callback);
}
dim(1, DURATION, 100, callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment