JavaScript: A Digital Clock with Johnny-Five

The Johnny-Five Tutorial Series is geared towards Arduino programming on Node.js, using the Johnny-Five framework. Get caught up here.


When I first started writing (copy and pasting) JavaScript in 1999, I focused solely on IE 5 (available on PC, Mac and UNIX; but I had no idea what it was truly capable of) and concerned myself with only a precious few novelties that could be included in a web page to quickly “enhance” the user’s experience. These enhancements included awful things like custom scroll areas, image roll-overs and dynamic clocks. It’s the last one that I want to revisit in this article, a decade and a half later, with a new perspective!

Before we get to the good stuff, let’s look at the bad stuff. A Google search for the term “javascript clock” reveals a pile of really crummy code snippets from some of the most suspect parts of the web. The following example is presented verbatim:

I’d like to make it unequivocally clear that this code is terrible and should never be used for anything more than illustrating the “wrong way”. However, despite being gruesome, this example is pretty straight forward: when the page loads (onload, HTML 4.01, 1999), call a function that writes a string representation of the current time (in hours, minutes and seconds) to the innerHTML (IE4, 1997) property of some DOM element.

A New Perspective

The decade-and-a-half-later perspective that I’m applying will take this example out of the browser and into the physical world. Here’s a list of parts to acquire before we get started:

Connect the following:

  • 8-Digit, 7-Segment LED Digits: J1
    • VCC to 5V
    • GND to GND
    • DIN to Digital 2
    • CS to Digital 3
    • CLK to Digital 4

It may be tempting to just port the previous code to our new program, as it would only require stripping the HTML, changing the digit separator and updating the target of the output.

function startTime() {
  var today=new Date();
  var h=today.getHours();
  var m=today.getMinutes();
  var s=today.getSeconds();
  m = checkTime(m);
  s = checkTime(s);
  // "print" is a stand-in for illustrative purpose only.
  print(h+"."+m+"."+s);
  var t = setTimeout(function(){startTime()},500);
}

function checkTime(i) {
  if (i<10) {i = "0" + i};  // add zero in front of numbers < 10
  return i;
}

// ... When appropriate:
startTime();

Taking this approach would be very common in 1999, but in 2014 we have nicer tools available to us; specifically, we’ll use moment.js to produce a nice time string which is modified ever-so-slightly with a Regular Expression (pdf link) replacement operation to match our desired format.

Save the following code as javascript-clock-irl-ftw.js:

var moment = require("moment");
var five = require("johnny-five");
var board = new five.Board();

board.on("ready", function() {
  var digits = new five.Led.Digits({
    pins: {
      data: 2,
      cs: 3,
      clock: 4,
    }
  });

  setInterval(function() {
    digits.print(time());
  }, 1000);
});

function time() {
  /*
    The desired display looks something
    like these examples:

      02.25.54 P
      12.30.00 A

    moment.js doesn't have an option for
    a single letter meridiem (nor should it,
    that would be silly), so we need to
    manipulate the string a bit so that
    it matches our desired display.
   */  return moment().format("hh.mm.ssA")
          .replace(/([AP])M/, " $1");
}

Run node javascript-clock-irl-ftw.js from your machine if using an Arduino, or on the device if using a Galileo.

Homework

Based on the program above, modify the code to cycle through a list of sensors connected to the board, displaying their current reading value.

Comments

We moved off of Disqus for data privacy and consent concerns, and are currently searching for a new commenting tool.

  1. I’m not being jerky here, so please take the following question as sincere.

    If you were just doing this in a browser (and not using a Johnny-Five board for the output), why would using moment.js be better than the simple example you copied from the Web?

    You say it’s the \”wrong way,\” I’m just curious why. It seems like using an external library and a regular expression to produce the time string seems a little heavy.

  2. It’s not like moment.js isn’t using the standard Date object, it’s just hassle free (and bug free) and easier to setup. You don’t have to deal with adding empty zeros, etc. I don’t think Rick claims that it’s the wrong way, he just prefers to use moment.js because it’s a good lib and makes his life easier. If it’s too heavy for your use, you can use the first example.

  3. Do you need a separate computer to do this if you already have an Internet enabled desktop and a wireless router? Can you simplify the setup by piggy-backing onto the existing hardware that the you already have?

    • Not sure what you mean? Once the program is written and scp’ed to the Galileo, I just SSH in and start the program. Galileo runs a Linux image (from an sd card) with node.js preinstalled. Hopefully that clarifies?

      • Perhaps what he means Rick is that if your desktop was old enough, it would have a parallel port that you could use to try driving the module with. I dont think you could manage it using a usb-serial cable, as the module needs 2 inputs plus the clk.

Contact Us

We'd love to hear from you. Get in touch!

Mail

P.O. Box 961436
Boston, MA 02196