LED animation using timer in CTC mode

Zápisník experimentátora

Hierarchy: Časovač (timer)

In today's article we will again look at the timer in CTC mode. We will demonstrate a simple animation with eight LEDs. Because the timer does all the work with timing animation, in the code we only have to write the appropriate code for the animation itself.

Used parts

To create an animation, we can use:

  • Arduino Pro Mini {linkArduino} - I used it because it will fit even the smallest breadboard.
  • Mini Breadboard {linkBreadboard} - The smallest sold breadboard.
  • Converter CP2102 USB to Serial {linkUSBSerial} - The converter is used to program the Arduino.
  • Board with resistors and LEDs (link) - Because I have made several such boards, I used it so I don't have to connect 8 LEDs and 8 resistors to the Arduina pin complicatedly. But you can also use directly resistors and LEDs, be careful not to exceed the maximum current on the pin. Therefore, use resistors from 330 to 1000 ohms.

Everything is connected as shown below. The LEDs are connected to pins 2-9 and the picture shows the GND connection on my LED board using two wire jumpers to Arduino. Arduino Pro Mini also has GND on the other side, so I could use a single jumper but then it would be badly photographed.


I used my app to create a 10 Hz timer. I set the required parameters in the interface and have the application skeleton generated. In the program, I also left the LED 13 flashing on the pin 13 to see the 10 Hz frequency on one LED.

CTC Timer kalkulačka

Then, adding an animation code was no more serious problem. The variable counter contains the current LED position. Takes values 0-7. The content of the setupTimer function is unchanged from the generator. In the setup function, pins 2-9 are set as output.

The interrupt handler is in ISR(TIMER1_COMPA_vect). In the cycle, I turn on the diode, which corresponds to the value of variable counter and the other diodes turn off. The last two lines ensure that the content of the variable counter is always only 0-7. The interruption occurs 10 times per second and because we have only eight diodes, you have the optical impression that it goes a bit faster.

#define ledPin 13
int counter = 0;

void setupTimer() {
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;

  OCR1A = 6249; // 10 Hz
  TCCR1A |= 0;
  TCCR1B |= (1 << WGM12);
  TCCR1B |= (1 << CS12) | (0 << CS11) | (0 << CS10);
  TIMSK1 |= (1 << OCIE1A);

void setup() {
  pinMode(ledPin, OUTPUT);

  for (int i = 2; i < 10; i++)
    pinMode(i, OUTPUT);


void loop() {

  digitalWrite(ledPin, digitalRead(ledPin) ^ 1);

  for (int i = 0; i < 8; i++)
    digitalWrite(i + 2, i == counter ? true : false);
  counter %= 8;

Source code

The source code is located on GitHub.