How to Use Timer as Counter in Embedded C: Simple Guide
In Embedded C, you use a hardware
timer as a counter by configuring the timer's control registers to count external events or clock pulses. This involves setting the timer mode to counter mode, enabling the clock source or external input, and reading the timer register to get the count value.Syntax
To use a timer as a counter, you typically configure these parts:
- Timer Control Register: Set mode to counter.
- Clock Source: Select external event or internal clock.
- Enable Timer: Start counting.
- Read Timer Register: Get current count value.
c
TIMER_CONTROL_REG = COUNTER_MODE | EXTERNAL_CLOCK_ENABLE;
TIMER_START();
// Later read count
count = TIMER_COUNT_REG;Example
This example shows how to configure a generic 16-bit timer as a counter for external pulses and read the count value.
c
#include <stdint.h> #include <stdio.h> // Simulated hardware registers volatile uint16_t TIMER_COUNT_REG = 0; volatile uint8_t TIMER_CONTROL_REG = 0; #define COUNTER_MODE 0x01 #define EXTERNAL_CLOCK_ENABLE 0x02 #define TIMER_ENABLE 0x80 void TIMER_START() { TIMER_CONTROL_REG |= TIMER_ENABLE; } void TIMER_STOP() { TIMER_CONTROL_REG &= ~TIMER_ENABLE; } uint16_t read_timer_count() { return TIMER_COUNT_REG; } int main() { // Configure timer as counter with external clock TIMER_CONTROL_REG = COUNTER_MODE | EXTERNAL_CLOCK_ENABLE; TIMER_START(); // Simulate external pulses incrementing the counter for (int i = 0; i < 10; i++) { TIMER_COUNT_REG++; } // Read the count uint16_t count = read_timer_count(); printf("Counted pulses: %u\n", count); TIMER_STOP(); return 0; }
Output
Counted pulses: 10
Common Pitfalls
Common mistakes when using timers as counters include:
- Not enabling the external clock source or input pin.
- Forgetting to start the timer after configuration.
- Reading the timer count before the counting is complete.
- Not handling timer overflow if the count exceeds the timer size.
c
/* Wrong: Timer not started */ TIMER_CONTROL_REG = COUNTER_MODE | EXTERNAL_CLOCK_ENABLE; // Missing TIMER_START(); /* Right: Start timer after config */ TIMER_CONTROL_REG = COUNTER_MODE | EXTERNAL_CLOCK_ENABLE; TIMER_START();
Quick Reference
| Step | Action | Description |
|---|---|---|
| 1 | Set Timer Mode | Configure timer control register to counter mode |
| 2 | Select Clock Source | Choose external event or clock input |
| 3 | Enable Timer | Start the timer to begin counting |
| 4 | Monitor Count | Read timer register to get count value |
| 5 | Handle Overflow | Check and manage timer overflow if needed |
Key Takeaways
Configure the timer control register to counter mode to count external events.
Always enable and start the timer after configuration to begin counting.
Read the timer count register to get the current count value.
Handle timer overflow to avoid incorrect counts in long counting periods.
Ensure the external clock source or input pin is properly enabled.