Animating with Code

Based on the Intro to Animation and Animations and Patterns pages.

Intro to Animation

How to use code to light up the display and make properly timed animation frames.

We will create “generative” art. Instead of having pre-drawn animation frames, we will let the computer generate them from scratch. image credit Mariya Krastanova

Timing

How does the computer keep time so that it knows when to change a frame?

Timing

int t = millis();

millis() gives the number of milliseconds since the device was turned on.

Every time the loop() block is run, millis() determines the number of milliseconds since setup() was run and stores it in the variable t.
Division of time into intervals of 2500. In this example, 5600 milliseconds have passed, which is 2 full cycles of 2500 milliseconds with a remainder of 600.
int t_repeating = t % 2500;
int t_repeating = t % 2500;
Using time to create a repeating pattern: the value returned by millis() (in blue) is divided into equal intervals. The remainder of that division (in orange) provides a steady repeating sequence of numbers on which we can base a repeating animation.

A picture that depends on time

void loop() {
  int t = millis();
  int t_repeating = t % 2500;
  int b = t_repeating / 10;
  SpinWheel.drawFrame();
}
Check out our lesson on the building blocks of coding to learn more about the essential pieces of writing a sketch. image credit Mariya Krastanova

Animations and Patterns

Common tools for more pleasant animations

Smoother pulsing

Instead of the pattern of brightness that abruptly dropped to zero that we saw previously, we can employ a pattern that also decreases steadily, making for a more pleasant pulsing light.

Examples → SpinWearables → Animations_and_Patterns → Smoother_Blink

void loop() {
}

The color wheel

The color wheel lets you generate a color based on a single continuously changing (maybe time-dependent) number. The red, blue and green components of the colors in the color wheel are shown in the plot on the right.
void loop() {
}

Animations_and_Patterns → Color_Wheel

Non-uniform patterns and accessing separate LEDs

void loop() {
}

Railroad_Signal

void loop() {
}

Rainbow_Chase

Overwhelmed by the possibilities of how you can modify the above sketches? Here are some suggestions:
  • Try to add more LEDs to your patterns.
  • Try to have some of them (e.g. the small ones) have varying brightness, while others (e.g. the large ones) have changing colors.
  • Mix and match code from the previous examples.

Let your creativity sing through the code!

// reveal.js plugins