Menu
CoddyTech

NeoPixel Clock: Mixing Hands

Part of the Projects section of Coddy's Arduino journey. Lesson 23 of 24.

The hours hand is red. A clock face shows 12 hours, so the hour is (now / 3600) % 12: 0 to 11, where 0 is 12 o'clock. That is already a pixel number.

Now hands can meet. At 10:24:52 the seconds hand is on pixel 10, on top of the hours hand. Drawn one after the other, the second covers the first and a hand disappears.

Light can mix instead. Give each hand its own colour part (red for hours, green for minutes, blue for seconds) and build every pixel from the hands on it:

for (int i = 0; i < pixelCount; i++) {
  int r = 0;
  int g = 0;
  int b = 0;
  if (i == hourPixel) {
    r = 255;
  }
  if (i == minutePixel) {
    g = 255;
  }
  if (i == secondPixel) {
    b = 255;
  }
  ring.setPixelColor(i, ring.Color(r, g, b));
}

Where hands meet, the parts add up: red and blue make magenta, green and blue cyan, red and green yellow. Every pixel is set on every pass, so the loop also replaces ring.clear().

challenge icon

Challenge

Hard

Add the hours hand and mix the hands:

  • the hour is (now / 3600) % 12, drawn on that pixel
  • build every pixel in a for loop: red 255 if the hours hand is there, green 255 for the minutes hand, blue 255 for the seconds hand

Press Run: the clock starts at 10:24:50 with the seconds and hours hands mixed. Then Check.

Try it yourself

#include <Adafruit_NeoPixel.h>

const int ringPin = 6;
const int pixelCount = 12;
Adafruit_NeoPixel ring(pixelCount, ringPin, NEO_GRB + NEO_KHZ800);

// The time the clock starts at, in seconds since midnight: 10:24:50
const unsigned long startTime = 10 * 3600UL + 24 * 60 + 50;

void setup() {
  ring.begin();
}

void loop() {
  unsigned long now = startTime + millis() / 1000;  // the time of day, in seconds
  int seconds = now % 60;
  int minutes = (now / 60) % 60;

  ring.clear();
  ring.setPixelColor(seconds / 5, ring.Color(0, 0, 255));  // seconds hand: blue
  ring.setPixelColor(minutes / 5, ring.Color(0, 255, 0));  // minutes hand: green
  ring.show();
  delay(100);  // redraw ten times a second
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Projects

Practice on your own: Arduino playground