Skip to content

Instantly share code, notes, and snippets.

@IainIsCreative
Last active March 26, 2018 14:20
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 IainIsCreative/d2157b93250d5f4cc43ad81a5920db62 to your computer and use it in GitHub Desktop.
Save IainIsCreative/d2157b93250d5f4cc43ad81a5920db62 to your computer and use it in GitHub Desktop.
Johnny-Five Smooth Hue Transition

Smooth RGB Hue Transition with Johnny-Five

This is a method of getting a smooth color transition from one color to the next for RGB Leds using Johnny-Five. The function changes the hue and goes through steps instead of just jumping to a color.

Required Packages

  • Johnny-Five
  • color-convert
  • Temporal (for non blocking sequences in place of setInterval.

Worthwhile Notes

It is worth noting that all that's happening is the hue changing. This method can be tested using REPL. Numbers must be between 0–360.

Since this is an RGB LED, be sure to use PWM (Pulse-Width Modulation) pins!

var five = require("johnny-five");
var temporal = require('temporal');
var colorConvert = require('color-convert');
var board = new five.Board();
board.on('ready', function() {
// Store RGB Led in a variable - note that it's using PWM pins!
var light = new five.Led.RGB({
pins: [9, 10, 11],
});
// Set a default color
var currentHue = 180;
// Convert the HSL color into a hex
var currentColor = colorConvert.hsl.hex(currentHue, 100, 50);
light.color(`#${currentColor}`);
/**
*
* colorTransition() function
*
* When the function is fired, check if the assigned color argument
* is different to the current hue. If true, then change
* the light in steps using a temporal loop.
*
* @param {Number} color - a number between 0-360 for the light's
* hue to change to.
*
*/
var colorTransition = function(color) {
// color argument does not match the current color? Start a loop!
if (color != currentHue) {
temporal.loop(50, (loop) => {
// If the new hue is higher in value than the current one, increment the hue.
// Otherwise, decrement the hue.
if (color > currentHue) {
currentHue++;
} else {
currentHue--;
}
// Write the new color to the light as the color value changes.
var newColor = colorConvert.hsl.hex(currentHue, 100, 50);
light.color(`#${newColor}`);
if (currentHue == color) {
// When the current hue matches the new color, stop the loop.
loop.stop();
}
});
}
}
// Allow REPL injection to test out the color transition function
this.repl.inject({
// changeColor() function to wrap the colorTransition() function
// @param {Number} color - the hue to change the color to.
changeColor: (color) => {
colorTransition(color)
},
});
// When closing the board, turn off the light, please.
this.on('exit', () => {
light.stop().off();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment