AI Binary Clock - LED Time Display Read time in binary! Six rows of glowing green LED circles repre

This sketch turns the current time into a glowing binary LED clock, splitting hours, minutes, and seconds into six decimal digits and lighting up green LED circles to represent each digit in binary. A readable HH:MM:SS readout sits below the LEDs so you can check your binary-reading skills against the real time.

🧪 Try This!

Experiment with the code by making these changes:

  1. Recolor the LEDs blue — Changing the fill color of lit LEDs turns the whole clock from green to blue instantly.
  2. Spread the LEDs wider apart — Increasing colSpacing pushes the LEDs further apart horizontally, making each row wider.
  3. Make the glow enormous — Boosting the glow circle's size creates a much dreamier, blurred-light look around every lit LED.
Prefer the full editor? Open it there →

📖 About This Sketch

This sketch creates a retro-style binary clock made of glowing green LED circles, arranged in six rows that represent the tens and ones digits of the hour, minute, and second. Each row lights up a pattern of 'on' and 'off' LEDs corresponding to the binary representation of that digit, with soft glow effects and highlights making the lit LEDs look like real illuminated bulbs. It relies on p5.js's built-in hour(), minute(), and second() functions along with JavaScript's Number.toString(2) and String.padStart() to convert decimal digits into binary strings.

The code is intentionally compact: a single setup() prepares a full-window canvas, and all the real work happens inside draw(), which recalculates the time every frame, converts it to six digits, and loops through rows and bits to draw each LED. By studying it you'll learn how to convert numbers to binary in JavaScript, how to lay out a responsive grid using width and height percentages, and how layered circles (glow, core, highlight) create a convincing lit-LED effect.

⚙️ How It Works

  1. When the sketch loads, setup() creates a canvas that fills the browser window and sets the font to monospace for the digital readout.
  2. Every frame, draw() clears the background and reads the current hour, minute, and second from the system clock.
  3. Those three numbers are split into six decimal digits (tens and ones for each of hour, minute, second), and each digit is converted into a binary string padded with leading zeros to match how many bits that digit needs.
  4. The sketch loops over the six rows top to bottom, and for each row loops over its bits left to right, drawing a bright glowing green circle for every '1' bit and a dim gray circle for every '0' bit.
  5. Below the LED grid, the sketch also prints the ordinary HH:MM:SS time as text so you can compare the binary pattern to the real time.
  6. If the browser window is resized, windowResized() rebuilds the canvas to match the new size so the layout stays centered and full-screen.

🎓 Concepts You'll Learn

Animation loopNumber-to-binary conversionNested for loopsResponsive layout with width/heightLayered transparency for glow effectsp5.js time functions

📝 Code Breakdown

setup()

setup() runs once when the sketch starts. It's the right place to configure the canvas size and any one-time settings like fonts, before draw() takes over every frame.

function setup() {
  createCanvas(windowWidth, windowHeight);
  textFont('monospace');
}
Line-by-line explanation (2 lines)
createCanvas(windowWidth, windowHeight);
Creates a canvas that exactly fills the browser window, using the window's current pixel dimensions.
textFont('monospace');
Sets the default font to a monospace typeface so the HH:MM:SS digits line up evenly, giving it a digital-clock look.

draw()

draw() runs continuously about 60 times per second. Because it re-reads hour(), minute(), and second() every frame, the clock automatically stays in sync with real time without any extra timer code - the animation loop itself acts as the clock's tick.

🔬 This block draws the glow at 4x the LED's radius. What happens visually if you change radius * 4 to radius * 8, or shrink it to radius * 2?

      // Draw glow first (bigger, semi-transparent circle)
      if (bitOn) {
        noStroke();
        fill(80, 255, 120, 70); // soft green glow
        circle(x, y, radius * 4);
      }

🔬 toString(2) converts a decimal digit to binary text. What do you think padStart(bits, '0') is for - try removing it (just use digit.toString(2)) and see what breaks when a digit like 3 needs to show as '0011' but becomes just '11'.

    const binStr = digit.toString(2).padStart(bits, '0');
function draw() {
  // Dark, slightly bluish background for contrast
  background(5, 10, 20);

  const h = hour();
  const m = minute();
  const s = second();

  // Split into decimal digits
  const digits = [
    floor(h / 10), h % 10,
    floor(m / 10), m % 10,
    floor(s / 10), s % 10
  ];

  const rows = digits.length;

  // Layout parameters
  const topMargin = height * 0.12;
  const bottomMargin = height * 0.30; // space for decimal time text
  const availableHeight = height - topMargin - bottomMargin;
  const rowSpacing = (rows > 1) ? availableHeight / (rows - 1) : 0;

  const maxBits = 4;                // maximum bits in any row
  const colSpacing = width * 0.08;  // horizontal distance between LEDs
  const radius = min(colSpacing * 0.3, rowSpacing * 0.25);

  // Draw each row (each decimal digit)
  for (let row = 0; row < rows; row++) {
    const y = topMargin + row * rowSpacing;
    const digit = digits[row];
    const bits = BIT_COUNTS[row];

    // Convert digit to binary string, padded to the right bit count
    // toString(2): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
    const binStr = digit.toString(2).padStart(bits, '0');

    // Center this row horizontally based on how many LEDs (bits) it has
    const rowWidth = (bits - 1) * colSpacing;
    const rowStartX = width / 2 - rowWidth / 2;

    for (let i = 0; i < bits; i++) {
      const x = rowStartX + i * colSpacing;
      const bitOn = binStr[i] === '1';

      // Draw glow first (bigger, semi-transparent circle)
      if (bitOn) {
        noStroke();
        fill(80, 255, 120, 70); // soft green glow
        circle(x, y, radius * 4);
      }

      // Core LED circle
      noStroke();
      if (bitOn) {
        fill(120, 255, 170); // bright green for "1"
      } else {
        fill(25, 45, 35);    // dark greenish gray for "0"
      }
      circle(x, y, radius * 2);

      // Small highlight for lit LEDs
      if (bitOn) {
        fill(255, 255, 255, 100);
        circle(x - radius * 0.4, y - radius * 0.4, radius * 0.7);
      }
    }
  }

  // Decimal time display under the binary LEDs
  const hStr = nf(h, 2); // nf(): https://p5js.org/reference/#/p5/nf
  const mStr = nf(m, 2);
  const sStr = nf(s, 2);

  fill(190);
  textAlign(CENTER, CENTER);
  textSize(min(width, height) * 0.06);
  text(`${hStr}:${mStr}:${sStr}`, width / 2, height - bottomMargin / 2);
}
Line-by-line explanation (15 lines)

🔧 Subcomponents:

calculation Split Time Into Digits const digits = [floor(h / 10), h % 10, floor(m / 10), m % 10, floor(s / 10), s % 10];

Breaks hour, minute, and second into six separate decimal digits (tens and ones) so each can be shown as its own binary row.

for-loop Row Loop for (let row = 0; row < rows; row++) {

Iterates over the six digit rows (H tens, H ones, M tens, M ones, S tens, S ones), positioning each one vertically.

for-loop Bit Loop for (let i = 0; i < bits; i++) {

Iterates over each binary digit (bit) in the current row, drawing one LED circle per bit.

conditional Glow Effect Check if (bitOn) { noStroke(); fill(80, 255, 120, 70); circle(x, y, radius * 4); }

Draws an extra-large, semi-transparent green circle behind lit LEDs to simulate a soft glow.

conditional LED Color Switch if (bitOn) { fill(120, 255, 170); } else { fill(25, 45, 35); }

Chooses bright green for a binary 1 or dark gray-green for a binary 0.

background(5, 10, 20);
Repaints the whole canvas with a very dark navy color every frame, erasing the previous frame's drawing so nothing smears.
const h = hour(); const m = minute(); const s = second();
Grabs the current hour (0-23), minute (0-59), and second (0-59) from the computer's clock using p5.js's built-in time functions.
const digits = [floor(h / 10), h % 10, floor(m / 10), m % 10, floor(s / 10), s % 10];
Splits each two-digit time value into its tens digit (integer division by 10) and ones digit (remainder with %), producing six separate digits to display.
const rows = digits.length;
Stores how many rows to draw - always 6, one per digit.
const topMargin = height * 0.12;
Reserves the top 12% of the screen height as empty space above the first LED row.
const bottomMargin = height * 0.30; // space for decimal time text
Reserves the bottom 30% of the screen for the HH:MM:SS text, keeping the LED grid from overlapping it.
const rowSpacing = (rows > 1) ? availableHeight / (rows - 1) : 0;
Divides the remaining vertical space evenly between the 6 rows so they're spread out from top to bottom.
const radius = min(colSpacing * 0.3, rowSpacing * 0.25);
Picks an LED radius small enough to fit both the horizontal spacing and vertical spacing, so circles never overlap regardless of screen shape.
const binStr = digit.toString(2).padStart(bits, '0');
Converts the digit to a base-2 (binary) string, then pads it with leading zeros so it always has the expected number of bits, e.g. 5 becomes '101' padded to '0101'.
const rowWidth = (bits - 1) * colSpacing; const rowStartX = width / 2 - rowWidth / 2;
Calculates the total width this row's LEDs will span and works out the starting x position so the row is centered horizontally on screen.
const bitOn = binStr[i] === '1';
Checks whether the current character in the binary string is '1', which determines if this LED should be lit.
circle(x, y, radius * 4);
Draws a large, mostly-transparent circle behind the LED to create a soft glow effect around lit bulbs.
circle(x, y, radius * 2);
Draws the main solid LED circle at twice the radius (its diameter).
circle(x - radius * 0.4, y - radius * 0.4, radius * 0.7);
Adds a small, semi-transparent white circle offset toward the upper-left to fake a shiny highlight on lit LEDs, like light reflecting off glass.
text(`${hStr}:${mStr}:${sStr}`, width / 2, height - bottomMargin / 2);
Draws the normal decimal time as text, centered horizontally and vertically within the reserved bottom margin area.

windowResized()

windowResized() is a special p5.js callback that fires automatically on browser resize events, letting you keep full-window sketches responsive without polling for size changes yourself.

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}
Line-by-line explanation (1 lines)
resizeCanvas(windowWidth, windowHeight);
Called automatically by p5.js whenever the browser window changes size; it resizes the canvas to match the new window dimensions so the layout recalculates in draw() and stays centered.

📦 Key Variables

BIT_COUNTS array

Stores how many binary bits each of the six digit rows needs (hours tens needs only 2 bits since it's 0-2, while ones digits need 4 bits since they go 0-9), so the sketch knows how many LEDs to draw and pad per row.

const BIT_COUNTS = [2, 4, 3, 4, 3, 4];

🔧 Potential Improvements (4)

Here are some ways this code could be enhanced:

STYLE draw()

The variable maxBits is declared with 'const maxBits = 4;' but never actually used anywhere in the function.

💡 Remove the unused maxBits declaration, or use it to validate/clamp bit counts if it was intended as a safety check.

PERFORMANCE draw()

Every frame recalculates topMargin, bottomMargin, colSpacing, and radius from scratch even though they only truly need to change when the window is resized.

💡 Move layout calculations into windowResized() (and call it once from setup()) so draw() only reads cached values instead of recomputing them 60 times per second.

FEATURE draw()

There's no visual indicator of which row corresponds to hours, minutes, or seconds, which can make the clock hard to read for newcomers.

💡 Add small text labels (e.g. 'H', 'M', 'S') to the left or right of each pair of rows using text() to help viewers learn to read it faster.

BUG draw() radius calculation

If the browser window is very narrow or very short, rowSpacing or colSpacing could become tiny or even negative-adjacent, making radius collapse to near zero and LEDs disappear.

💡 Add a constrain() call around radius, e.g. radius = constrain(min(colSpacing * 0.3, rowSpacing * 0.25), 2, 40), to guarantee LEDs stay visible on extreme window sizes.

🔄 Code Flow

Code flow showing setup, draw, windowresized

💡 Click on function names in the diagram to jump to their code

graph TD start[Start] --> setup[setup] setup --> draw[draw loop] draw --> digit_split[Digit Split] draw --> row_loop[Row Loop] row_loop --> bit_loop[Bit Loop] bit_loop --> glow_conditional[Glow Effect Check] glow_conditional --> color_conditional[LED Color Switch] color_conditional --> draw click setup href "#fn-setup" click draw href "#fn-draw" click digit_split href "#sub-digit-split" click row_loop href "#sub-row-loop" click bit_loop href "#sub-bit-loop" click glow_conditional href "#sub-glow-conditional" click color_conditional href "#sub-color-conditional"

❓ Frequently Asked Questions

What visual experience does the AI Binary Clock sketch provide?

The AI Binary Clock visually represents time using six rows of glowing green LED circles, displaying the current hours, minutes, and seconds in binary format.

Is the AI Binary Clock interactive, and how can users engage with it?

The AI Binary Clock is not interactive; it continuously updates to show the current time in real-time, allowing users to observe the binary representation.

What creative coding concepts are showcased in the AI Binary Clock sketch?

This sketch demonstrates binary number representation and dynamic visual updates using p5.js, illustrating how to convert decimal time into binary format for a unique display.

Preview

AI Binary Clock - LED Time Display Read time in binary! Six rows of glowing green LED circles repre - p5.js creative coding sketch preview
Sketch Preview
Code flow diagram showing the structure of AI Binary Clock - LED Time Display Read time in binary! Six rows of glowing green LED circles repre - Code flow showing setup, draw, windowresized
Code Flow Diagram