Arduino & Atmel Studio 7 — CTC Mode

A Quick Study on CTC (Clear Timer on Compare) — Ardu_Serie #43

J3
Jungletronics

--

Hello Hobbyists! Let’s dive into practice and study a subject that is feared by beginners that it is microcontroller interruption; At Arduino, we will see step-by-step how to use the CTC Mode feature in our projects. Let’s get started!

Yep, let’s see…you may not even know that many Arduino functions use timers: delay(), millis() and micros() and delayMicroseconds(); The PWM function analogWrite() uses timers, as do the tone() and the noTone() functions. And the Servo library uses timers and interrupts.

The Arduino API makes it all transparent to you!

After all, what are timers?

It is like a clock and can be used to measure time events.

In the Arduino firmware, all timers were configured to a 1kHz frequency and interrupts are generally enabled.

The Arduino controller — our object of this study, Atmega328p, has 3 timers: Timer0 (8-bits), Timer1(16-bits) and Timer2 (8-bits).

8-bits means 256 values whilst 16-bit means 65536 values for higher resolution or the long count.

All timers depend on the system clock of your Arduino. The Arduino system clock is 16MHz.

The timer hardware can be configured with some special timer registers.

In order to change Timer behavior of your Arduino, these are the registers to manipulate (concerned about CTC mode;)

TCCRx — Timer/Counter Control Register. The Prescaler can be configured here;

TCNTx — Timer/Counter Register. The actual timer value is stored here;

OCRx — Output Compare Register;

DDRx —Control whether the pins in PORTx are configured as Input or Output;

PORTx — Is the register for the state of the outputs;

TIFRx — Timer/Counter Interrupt Flag Register.; Indicates a pending timer; interrupt.

But wait…What the hell is CTC mode??

Here is a breeze …

In what concerns CTC mode we will work on a step-by-step base code that will generate a pulse on pin 13, those very ones with in-build LED that comes on the every Arduino board:D

I’m going to use hereafter in my projects the Arduino multi-function shield (available from Hobby Components and other internet suppliers):

http://blog.eletrogate.com/guia-completo-do-shield-multi-funcoes-para-arduino/

Why ???

…to avoid protoboard at all cost... Just study the connections and we will easily repeat the experiment if necessary to use the infamous protoboards:/

We need to flash an LED every 100 ms using CTC Mode. We have a crystal of XTAL 16 MHz (calc in code…:)

#Step_01—First Shot — The Code:

Run this code on Atmel Studio 7 (see video):

Wait…Send to Arduino? Where is this menu? How to load programs to an Arduino UNO from Atmel Studio 7

All we see is the LED on port 13 flashing at 10 hertz, so what? 😮

Here’s what: probing PIN 13 by SoundCard Oscilloscope and we get this:

10 Hertz pulse on Arduino PIN 13 (… quite actually: 9.9491Hz;-)

How we do it? Here is the above code explained:

#Step_02 — Understanding timer initializer code;

interrupt and variable and setting up timer with Prescaler = 1024 and CTC mode, ugh!!! Take it easy!

First the time initializer:

TCCR2A |= (1 << WGM21) | (0 << WGM20);TCCR2B |= (0 << WGM22) | (1 << CS22) | (1 << CS21) | (1 << CS20);

Do it: open the Atmega328P datasheet CTRL + F and type TCCR2A;

TCCR2A— TC2 Control Register A

TCCR2A |= (1 << WGM21) | (0 << WGM20);

TC2 Control Register A (controls the wave generation — sawtooth, in the case) works together with the next 8-bit register, TCCR2B, in compare output mode, non-PWM;
TCCR2A is 8 bits: [COM2A:COM2A0:COM2B1:COM2B0:unused:unused:WGM21:WGM20];
1<<WGM21: sets bit WGM21(Waveform Generation Mode Bit, Timer 2, 1th reg), which begins to form the bits 010 corresponding to CTC Mode 2 ( WGM22:WGM21:WGM20), the required configuration, see Table 22–9. Waveform Generation Mode Bit Description on Data sheet page 205;
0 << WGM20: resets bit WGM20(Waveform Generation Mode Bit, Timer 2, 0th reg), see explanation above: 010 (WGM22:WGM21:WGM20);

TCCR2B — TC2 Control Register B

TCCR2A |= (0 << WGM22) | (1 << CS22) | (1 << CS21) | (1 << CS20);

TC2 Control Register B (controls the wave generation completing CTC Mod — WGM22:WGM21:WGM20 — work with TCCR2A, see above);
TCCR2B is 8 bits: [FOC2A:FOC2B:unused:unused:WGM22:CS22:CS21:CS20];
0 <<WGM22: resets bit WGM22( finishes the setup started on the previous register by resetting bits 010 corresponding to CTC Mode (WGM2: WGM21:WGM20), according to the required configuration, see reg TCCR2A; 1<<CS22: sets bit CS22 ( Clock Select, Timer 2, 2th reg), which puts the prescale to 1024 (111);
1<<CS21: sets bit CS21( Clock Select, Timer 2, 1th reg), which puts the prescale to 1024 (111);
1<<CS20: sets bit CS20( Clock Select, Timer 2, 0th reg), which puts the prescale to 1024 (111); (datasheet page 207);

#Step_03 — Now go again to Atmega321p data sheet

and reach up item 22.11.3. TC2 Counter Value Register, page 208;

TCNT2 = 0; 

This forces the zero-initializing of the counter value; I'd rather not trust hardware warranties ...

#Step_04— Initialize compare value to 10 Hz,

which finalizing the CTC mode 2 configuration, closing the function : void timer2_init();

OCR2A = 156;

OCR2A: Output Compare Register, Timer 2, Channel A contains an 8-bit value that is continuously compared with the counter value (TCNT2);

In Clear Timer on Compare or CTC mode (WGM2[2:0] = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence also its resolution. This mode allows greater control of the compare match output frequency. It also simplifies the operation of counting external events.

The timing diagram for the CTC mode is illustrated in the video above … watch before you go … The counter value (TCNT2) increases until a compare match occurs between TCNT2 and OCR2A, and then counter (TCNT2) is cleared.

#Step_05 — Now it is enough to select which PIN…

…(PINB5) you want the output, initialize the Timer2 in CTC mode and toggle the LED (PORTB ^= (1 << PINB5);-) connected to the pin…voilà!!! See this video.

#Step_06 — Good, our first goal is reached, but there are more miles…

…Interruptions…yeap! since now we are using a polling technique! Interruptions free up the processor and pass the responsibility to the hardware (see in the code a bunch of commented lines …).

This is the register to deal with:

TC2 — Interrupt Mask Register

OCIEA|= (1 << OCIEA); Timer/Counter2, Output Compare A Match Interrupt Enable (enables interruption of the channel A, Timer2)
TIMSK2 is 8 bits: [unused:unused:unused:unused:unused:OCIEB:OCIEA:TOIE]
1<<OCIEA: sets bit OCIEA (Interrupt Enable, channel A, 1th bit), which puts the interruption on work each time OCR2A = TCNT2;

Here’s the code modifications:

Modification: include int library;

2ª Modification: enable CTC, Timer2, Ch A interruptions;

Modification: set Global Interrupt Enable;

Modification: Implement ISR (fired whenever a match occurs);

Modification: empty while():D

#Step_07— The final step and get rid of even the ISR routine... How?

Using the signal output pin generated by the CTC mode on OCnx pin. As we are dealing with Timer 2, Channel A, the pin is OC2A (see the pinout of the ATmega328/P chip below).

Hurrah! That’s the code’s maximum perfection, is not it ?!

Outputting to OCnx pin :-)

Go to ATmega328P datasheet, type TCCR2A and…

TCCR2B — TC2 Control Register B

TCCR2A |= (1 <<COM2A0) |(0 << WGM22) | (1 << CS22) | (1 << CS21) | (1 << CS20);

TC2 Control Register B (controls the wave generation completing CTC Mode -WGM22:WGM21:WGM20 — work with TCCR2A, see above);
TCCR2B is 8 bits: [FOC2A:FOC2B:unused:unused:WGM22:CS22:CS21:CS20];

1 <<COM2A0: sets bit COM2A( Toggle OC2A on Compare On Match Mode);

Now :

1ª Modification: insert (1 << COM2A0);

2ª Modification: Delete ISR altogether!;

3ª Modification: connect led to pin PB3 — Arduino PIN D11;

http://arduinolearning.com/code/multi-function-shield-examples.php

See in this video that by using CTC Mode in all its mystery and plenitude, the output pin is D11 for Arduino parlance — or PB3 for Atmega328P chip — or OC2A — output pin for the Timer2:-)

There you have it!

That’s all!

…Thanks for you guys for reading this post / watching my youtube video / whatever ;).

In my Channel, Hit the like button if you like my youtube video though subscribe to the channel to get notified when I put out new videos and I’ll see you again next time.

Bye!

References and Credits

http://maxembedded.com/2011/07/avr-timers-ctc-mode/

GitHub

My YouTube Channel Playlist

Facebook

Tweeter

Atmega328P Datasheet

Soundcard Oscilloscope

Cohesive Computing

Driving 595 Shift Registers

MAKE: PROJECTS Sound Card Oscilloscope

Arduino’s Oscilloscope Right Now !!! 04 #arduSerie

Free slide: Enjoy ctc dance:) https://docs.google.com/presentation/d/e/2PACX-1vTNV7l-5DYzvK0EBAcX9cEI2hn7HTycZd7PhLb0qyMgS6qDFjK6qkekIx1gALzPkOTaljK4auCy5ILe/pub?start=true&loop=false&delayms=3000

Troubleshooting

1-In the case your system did not recognize where Arduino's PORT are running, open Atmel Studio 7 menu Tools > External Tools > Arguments and find this line and modify the part corresponding to your port (bold):

Arguments
-CC:\arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM10 -b115200 -D -Uflash:w:”$(ProjectDir)Debug\$(TargetName).hex”:i

2-Wait…Send to Arduino? Where is this menu? How to load programs to an Arduino UNO from Atmel Studio 7

3- you name it…please contact me…

Download All Files From Google Drive

A new technology will come along to fix the messes we made with the last one.

<First Published on Aug / 2018>

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!