Arduino Counter Timer Mode Tutorial & Code Examples

In this tutorial, we’ll discuss Arduino Counter Timer Mode from the very basic concepts all the way to implementing Arduino Counter Timer Mode applications. We’ll start off by discussing what is a timer, how it works, what are different timer operating modes, and the working principles of Arduino timers in counter mode.

We’ll create a couple of Arduino Counter Timer Example Code Projects in this tutorial to practice what we’ll learn all the way through. And finally, we’ll draw some conclusions and discuss some applications & use cases for Arduino Timer (Counter Mode) that will definitely help you take some guided design decisions in your next projects. Without further ado, let’s get right into it!

Table of Contents

  1. Arduino Timers
  2. Arduino Counter Timer Mode
  3. Arduino Counter Timer Code
  4. Arduino Counter Timer Example
  5. Arduino Counter Timer Applications
  6. Arduino Counter Wrap Up

Arduino Timers

Timer modules in Arduino provide precise timing functionality. They allow us to perform various tasks, such as generating accurate delays, creating periodic events, measuring time intervals, and meeting the time requirements of the target application.

Each Arduino board has its target microcontroller that has its own set of hardware timers. Therefore, we always need to refer to the respective datasheet of the target microcontroller to know more about its hardware capabilities and how to make the best use of it.

1. Arduino Hardware Timers

Arduino UNO (Atemga328p) has 3 hardware timers which are:

  • Timer0: 8-Bit timer
  • Timer1: 16-Bit timer
  • Timer2: 8-Bit timer

Those timer modules are used to generate PWM output signals and provide timing & delay functionalities to the Arduino core, and we can also use them to run in any mode to achieve the desired functionality as we’ll see later on in this tutorial.

Each hardware timer has a digital counter register at its core that counts up based on an input clock signal. If the clock signal is coming from a fixed-frequency internal source, then it’s said to be working in timer mode. But if the clock input is externally fed from an IO or any async source, it’s said to be working as a counter that counts incoming pulses.

2. Arduino Timer Prescaler

A prescaler in a hardware timer module is a digital circuit that is used to divide the clock signal’s frequency by a configurable number to bring down the timer clock rate so it takes longer to reach the overflow (maximum count number).

This is really useful to control the maximum time interval that can be generated using the timer module, the PWM output frequency, or the range of time that can be measured using the timer module.

Running the timer module at the system frequency is good for resolution but will generate so many timer overflow interrupts that needs extra care in your code. Hence, using a prescaler can be useful to avoid this situation in the first place if needed.

In timer mode, the timer module will have the internal clock of the system as a clock source and it passes through the prescaler as shown below. You can programmatically control the division ratio of the prescaler to control the timer input clock frequency as you need.

STM32 Timers Explained Tutorial With Modes PWM Encoder

The timer prescaler divider values differ from one timer module to another and it’s clearly stated in the datasheet for each timer module (Timer0, 1, and 2).

3. Arduino Timers Comparison

This is a summarized table for Arduino UNO (Atmega328p) timers, differences between them, capabilities, operating modes, interrupts, and use cases.

Timer0Timer1Timer2
Resolution8 Bits16 Bits8 Bits
Used For PWM Output Pins#5, 69, 1011, 3
Used For Arduino Functions delay()
millis()
micros()
Servo Functions tone()
Timer Mode
Counter Mode
Output Compare (PWM) Mode
Input Capture Unit Mode
Interrupts Vectors TIMER0_OVF_vect
TIMER0_COMPA_vect
TIMER0_COMPB_vect
TIMER1_OVF_vect
TIMER2_COMPA_vect
TIMER1_COMPB_vect
TIMER1_CAPT_vect
TIMER2_OVF_vect
TIMER2_COMPA_vect
TIMER2_COMPB_vect
Prescaler Options1:1, 1:8, 1:64, 1:256, 1:10241:1, 1:8, 1:64, 1:256, 1:10241:1, 1:8, 1:32, 1:64, 1:128, 1:256, 1:1024
❕ Note

Playing with any timer configurations can and will disrupt the PWM output channels associated with that module. Moreover, changing the configurations of timer0 will disrupt the Arduino’s built-in timing functions ( delay, millis, and micros). So keep this in mind to make better design decisions in case you’ll be using a hardware timer module for your project. Timer1 can be the best candidate so to speak.

4. Arduino Timers Control Registers

We can initialize, configure, and control Arduino Timers & Timer Interrupts using the associated registers as stated in the datasheet. The Timer-associated registers are as follows:

  • TCCRxA: Timer/Counter Control Register A.
  • TCCRxB: Timer/Counter Control Register B.
  • TCNTx: Timer/Counter Registers.
  • OCRxA: Output Compare A Register.
  • OCRxB: Output Compare B Register.
  • TMISKx: Timer Interrupts Mask Register, enable/disable timer interrupts.
  • TIFRx: Timer interrupts Flag Bits Register, read/clear timer interrupt flag bits.

Where x can be 0, 1, or 2 for timers (Timer0, Timer1, and Timer2) respectively. More details on the functionality that each bit controls and what are its different options can be found in the datasheet of the microcontroller.

For more information about Arduino Timers, fundamental concepts, different timer operating modes, and code examples, it’s highly recommended to check out the tutorial linked below. It’s the ultimate guide for Arduino Timers.

???? Also Read
Arduino Timers Tutorial [Ultimate Guide]

This article will give more in-depth information about Arduino Timers, how timers work, different timer operating modes, practical use cases and code examples, and everything you’d ever need to know about Arduino Timers.


Arduino Counter Timer Mode

The timer module in counter mode is configured to have an external pin as the clock source with multiple prescaler options. It’s generally used to count external input pulses or measure an input signal by counting its rising or falling edges over a fixed time interval.

There are so many applications and use cases for timer modules in counter mode as we’ll see later on. Here is the block diagram for the hardware timer in counter mode.

As you can see, the Tn pin is the input pin to the timer’s clock source. This is the major difference between a hardware timer working in Counter Mode vs Timer Mode. The Timer input pin (Tn) can be hooked up to a push button and we can use it to count the pulses generated when we click on the button.

The timer module in counter mode can be set to count up each RISING or FALLING edge on the Tn input pin.

STM32 Timers Explained Tutorial Counter Mode Encoder

You can refer to the Arduin UNO Pinout Guide to identify all timer input pins (Tn). Where T0 is the Timer0 input pin and T1 is the Timer1 input pin. In Arduino UNO (Atmega328p), the T0 & T1 pins are Arduino IO pins (4 & 5) respectively. Also note that: the Counter0 register (TCNT0) is 8 bits, while the Counter1 register (TCNT1) is 16 bits.

❕ Note

Timer2 doesn’t have an input pin so it doesn’t operate in counter mode.


Arduino Counter Timer Code

To set an Arduino Timer module to operate in counter mode, we’ll use the clock selection bits in the TCCRxB register. Here are the counter mode clock options for the least significant 3 bits in the TCCRxB register (as stated in the datasheet).

Arduino-Counter-Timer-Registers

Here is an example of an Arduino Counter Timer Code that sets Timer1 to operate in Counter Mode (counts up every RISING edge on the T1 pin). The counter register’s value is sent to the PC over the serial port 4 times per second.


Arduino Counter Timer Example

In this example project, we’ll test Arduino Timer1 Counter Mode. We’ll use Timer1 in counter mode with the Tn input pin clocking the timer module on RISING edge events. We’ll hook up a push button to the Tn input pin to count the pulses using Timer1 in counter mode.

We’ll periodically read the timer counter register (TCNT1) and send its value over the serial port to the PC and display it.

Wiring

Here is how to hook up the timer input pin (T1 or IO pin5) to the push button with a pull-down 10kΩ resistor.

Arduino-Counter-Example-Code-Wiring

Arduino Counter Timer Example Code

Here is the full code listing for this Arduino Timer Interrupt Example.

Code Explanation

setup()

in the setup() function, we’ll configure & initialize the Timer1 module to operate in Counter Mode. And we’ll also initialize the serial port (UART) to work @ 9600bps. No need to set the pinMode for the Tn pin as an input, because it’s by default is.

loop()

in the loop() function, we read the Timer1 counter register (TCNT1) and send its value over UART 4 times per second.

Proteus Simulation

Here is the simulation result for this project on the Proteus (ISIS) simulator. The TinkerCAD simulation for this example will not produce a reliable behavior maybe due to inaccuracies in the microcontroller model in the simulation environment. The proteus simulation is way more accurate and behaves exactly like the real Arduino UNO board.

Moreover, we’ve got a better and much more powerful set of virtual measurement tools (oscilloscope, function generator, multimeters, virtual serial terminal, etc).

Check out the tutorial below to help you get started with simulating your Arduino projects in the Proteus simulation environment.

???? Also Read
Arduino Proteus Library Simulation Guide

This article will provide you with more in-depth information about using proteus ISIS for Arduino projects simulation.

Testing Results

Here is the result of running this example project on my Arduino UNO board and showing the result on the serial monitor.

Remarks on Arduino Counter Example

From the testing results of this example project, you can easily notice that the counter value is jumping (skipping) a couple of pulses every now and then. This is not an issue in the code or the timer module’s counter itself.

This issue is commonly known as “Button Bouncing“. This is simply a random event due to the button’s mechanical contacts bouncing, which results in some glitches or unintended pulses being injected into the digital input pin (Tn) causing it falsely send multiple clocks to the counter register.

Despite the fact that there are so many software button debouncing techniques (algorithms) that you can learn about from the guide below, it still won’t protect an external timer input pin because the hardware bouncing is sending a random triggering signal to the counter register.

The best way to deal with it and prevent false interrupt triggering is to use hardware button debouncing which is also demonstrated in the guide tutorial below with a lot of examples.

???? Also Read
Arduino Button Debouncing Tutorial

This article will provide you with more in-depth information about Arduino button debouncing techniques both hardware & software methods. With a lot of code examples & circuit diagrams.


Arduino Counter Timer Applications

There are so many applications and use cases for timer modules in counter mode. In this section, we’ll discuss some of the most common counter-mode applications that you need to know to make the best use of it if you need it in your next project.

1. Pulse Counting

You can use the Timer in Counter Mode to count the number of pulses generated by external devices or sensors. For instance, you can count the number of revolutions of a motor shaft, the number of pulses from an encoder, or the number of times a button is pressed.

2. Frequency Measurement

By counting the input signal pulses over a fixed time interval, we can easily identify the input signal’s frequency. This is a very common application for timer modules in the counter mode that’s used in devices like (tachometers or motor RPM speed measurement).

We can also build a frequency counter project based on the Arduino’s timer in counter mode.

3. Event Synchronization

By connecting an external signal with a known frequency to the timer input pin, you can measure time intervals, generate accurate time delays, or synchronize actions based on specific timing requirements. For instance, you can trigger an action or activate a device after a certain number of pulses have been counted.

4. Extra External Interrupt Pin

One obscure application for timer modules in counter mode is to use the timer input pin (Tn) as an additional external interrupt pin with a dedicated interrupt vector. You can consider it exactly like (INT0 & INT1) pins. If you’re desperate for one more dedicated interrupt pin like (INTx) not (PCINT), then a timer module in counter mode can be an exotic solution for such a situation.

Here is how it’s done: set the time in counter mode and preload the timer counter register with the maximum value (255 or 65535) depending on the timer resolution. Now, the timer module is on the edge of overflow, one RISING or FALLING edge on the Tn pin, and an OVF interrupt will be fired.

In the ISR, preload the timer counter register with the Max value again and keep going. Now you have the Tn pin working as a dedicated interrupt pin with a dedicated interrupt vector TIMERx_OVF_vect, and that’s it!


Parts List

Here is the full components list for all parts that you’d need in order to perform the practical LABs mentioned here in this article and for the whole Arduino Programming series of tutorials found here on DeepBlueMbedded. Please, note that those are affiliate links and we’ll receive a small commission on your purchase at no additional cost to you, and it’d definitely support our work.

Download Attachments

You can download all attachment files for this Article/Tutorial (project files, schematics, code, etc..) using the link below. Please consider supporting my work through the various support options listed in the link down below. Every small donation helps to keep this website up and running and ultimately supports our community.


Arduino Counter Wrap Up

To conclude this tutorial, we’d like to highlight the fact that the Arduino Timers in Counter Mode are very useful in so many applications as we’ve discussed earlier. You can easily set up an Arduino timer to operate in Counter Mode and count the incoming pulses on the Tn input pin.

This tutorial is a fundamental part of our Arduino Series of Tutorials because we’ll build on top of it to interface various sensors and modules with Arduino in other tutorials & projects. So make sure you get the hang of it and try all provided code examples & simulations (if you don’t have your Arduino Kit already).

If you’re just getting started with Arduino, you need to check out the Arduino Getting Started [Ultimate Guide] here.

???? Also Read
Getting Started With Arduino Programming For Beginners

This is the ultimate guide for getting started with Arduino for beginners. It’ll help you learn the Arduino fundamentals for Hardware & Software and understand the basics required to accelerate your learning journey with Arduino Programming.

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Khaled Magdy
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

Leave a Comment