To use counter, we must work with CS02:00 of the TCCR0 register.
- Timer/Counter Control Register 0 (TCCR0)
BIT 7 | BIT 0 | ||||||
FOC0 | WGM00 | COM01 | COM00 | WGM01 | CS02 | CS01 | CS00 |
When the CS02:00 = 0x06 , then TCNT0 count the falling edge pulse clock fed to pin PB0/T0.
When the CS02:00 = 0x07, then TCNT0 count the rising edge pulse clock fed to pin PB0/T0.
TCNT0 is 8-bit wise read/write register. It counts from 0x00 to 0xFF. When its value rolls from 0xFF to 0x00, then the TOV0 flag is set.
00:00 / 00:00
We can count any value larger than 0xFF by working with TOV0, and adding more variables with programming technique.
In this example, I create a counter device display the counting result up to 9999.
Source code is here:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <avr/io.h> | |
#define F_CPU 4000000UL | |
#include <util/delay.h> | |
unsigned int counter_0=0; | |
void displaySSD(void){ | |
unsigned char ssd[16]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D, | |
0x07,0x7F,0x6F,0x77,0x7C,0x39,0x5E,0x79,0x71}; | |
//Digit 1 1000's | |
PORTD=0b00001100; | |
PORTC=ssd[counter_0/1000]; | |
PORTD=0b00011100; | |
_delay_ms(10); | |
//Digit 3 100's | |
PORTD=0b00001100; | |
PORTC=ssd[(counter_0%1000)/100]; | |
PORTD=0b00101100; | |
_delay_ms(10); | |
//Digit 2 10's | |
PORTD=0b00001100; | |
PORTC=ssd[(counter_0%100)/10]; | |
PORTD=0b01001100; | |
_delay_ms(10); | |
//Digit 1 1's | |
PORTD=0b00001100; | |
PORTC=ssd[counter_0%10]; | |
PORTD=0b10001100; | |
_delay_ms(10); | |
} | |
int main(void) | |
{ unsigned int temp=0; | |
DDRC=0xFF; | |
DDRD=0xFF; | |
TCCR0=0x07; | |
TCNT0=0; | |
TIFR=0x01; | |
while (1) | |
{ | |
displaySSD(); | |
/*When counter 0 overflow | |
add 0xFF the holding register*/ | |
if (TIFR&0x01) | |
{ | |
temp+=0xFF; | |
TIFR=0x01; | |
} | |
counter_0=temp+TCNT0; | |
/*Reset the display whenever | |
the total pulse exceed 10000*/ | |
if (counter_0>=10000) | |
{ | |
temp=0; | |
counter_0=0; | |
TCNT0=0; | |
} | |
} | |
} |
A screen shot of this program.
![]() |
A simulation screen shot. The counting reaches 2179 with some bugs. |
Back to main tutorial page ATMega32 tutorials in C with Atmel Studio 7.
If you want a standard PCB for ATMega32 micro-controller, you can order my AVR Microcontroller project from PCBWay with a reasonable price. Click here to get a free $5 credit for new account.
No comments:
Post a Comment