The Timer/Counter1 module of Atmega32 is able to count external pulse. It has a 16-bit counter/timer registers pair, TCNT1H and TCNT1L. We need to select its clock source of the Timer/Counter1 Control Register B - TCCR1B to allow this module working in external event counting mode. It work in two clock transitions, falling edge and rising edge. The clock source must be point to T1 (PB1) pin.
Running program in Proteus Simulator |
It also have a pre-scaler to divide a number of input clock pulse. Basically I will need only the TCCR1B, TCNT1H, and TCNT1L register to make this module operate in external counting mode.
- Timer/Counter1 Control Register B - TCCR1B
Timer/Counter1 Control Register B - TCCR1B |
Clock Select Bit Description
|
I choose the "External clock source on T1 pin. Clock on rising edge". So CS12, CS11, and CS10 will set.
- Timer/Counter1 - TCNT1H and TCNT1L Register
Timer/Counter1 – TCNT1H and TCNT1L Registers |
This register composes of two 8-bit registers pair, TCNT1H and TCNT1L. They are readable and writable.
In this example, I make a counting system that could count up to 10000 before it rolls down. Since this register is 16-bit it maximum value is 65536 values. But it's not necessary here.
/* * m32Counter1MuxDisplay.c * * Created: 7/9/2022 6:10:41 PM * Author : aki-technical */ #include <avr/io.h> #define F_CPU 4000000UL #include <util/delay.h> int main(void) { int temp; /*Common Cathode Display*/ unsigned char displayData[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F}; /*PortB and PortD Output*/ DDRC=0xFF; DDRD=0xFF; /*Select T1 Clock in, rising edge*/ TCCR1B|=(1<<CS12)|(1<<CS11)|(1<<CS10); /*Clear Timer/Counter1*/ TCNT1H=0; TCNT1L=0; while (1) { /*Read the 16-bit counter registers*/ temp=(TCNT1H<<8)+TCNT1L; /*Reset if it reaches 10000*/ if (temp>9999) { temp=0; TCNT1H=0; TCNT1L=0; } /*Display processing*/ PORTD=0x00; PORTC=displayData[temp/1000]; PORTD=0x01; _delay_ms(5); PORTD=0x00; PORTC=displayData[(temp%1000)/100]; PORTD=0x02; _delay_ms(5); PORTD=0x00; PORTC=displayData[(temp%100)/10]; PORTD=0x04; _delay_ms(5); PORTD=0x00; PORTC=displayData[temp%10]; PORTD=0x08; _delay_ms(5); } }
Click here to download its source file.
No comments:
Post a Comment