Skip to content

Instantly share code, notes, and snippets.

@jimoneil
Created March 16, 2015 23:56
Show Gist options
  • Save jimoneil/2c8d406031c375f444bd to your computer and use it in GitHub Desktop.
Save jimoneil/2c8d406031c375f444bd to your computer and use it in GitHub Desktop.
Chuck Norris Edison IoT Demo
var request = require('request');
var mraa = require('mraa');
var myButton = new mraa.Gpio(3);
myButton.dir(mraa.DIR_IN);
var LCD = require('jsupm_i2clcd');
var myLCD = new LCD.Jhd1313m1(0, 0x3E, 0x62);
var processingRequest = false;
function readButton()
{
if (myButton.read() && !processingRequest)
{
processingRequest = true;
showJoke();
}
}
setInterval(readButton, 250);
var showJoke = function() {
request.get('http://api.icndb.com/jokes/random',
function (error, response, body) {
if (!error && response.statusCode == 200) {
var joke = JSON.parse(body).value.joke;
outputLines(0, linifyJoke(joke, 16));
}
}
)};
var i = 0;
var outputLines = function(i, lines)
{
setTimeout(function()
{
myLCD.setCursor(0,0);
myLCD.write(lines[i]);
myLCD.setCursor(1,0);
i++;
if (i < lines.length)
{
myLCD.write(lines[i]);
}
else
{
myLCD.write(pad(" ", 16));
}
if (i + 1 < lines.length)
outputLines(i + 1, lines);
else
processingRequest = false;
}, 2500);
};
var pad = function(s, l)
{
for(i=s.length; i<l; i++)
s = s.concat(" ");
return s;
}
var linifyJoke = function(joke, lineLength)
{
var wordNumber = 0;
var words = joke.split(" ");
if (words.length == 0) words.push("No joke for you!");
var lines = [];
var line = "";
do
{
var word = words[wordNumber];
if (word.length + line.length < lineLength)
line = line.concat(line.length > 0 ? " " : "", word);
else
{
lines.push(pad(line, lineLength));
line = word;
}
wordNumber++;
} while (wordNumber < words.length);
lines.push(pad(line, lineLength));
return lines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment