Generate pulse with timer1 in normal mode in ATmega 2560 using TOV flag

avrcmicrocontroller

Timer have CTC and PWN for generating pulse. However if I want to generate pulse when timer reach its max level then using CTC or PWN is somehow not needed when the TOV is set whenever timer overflown. My idea is that the output pin will toggle whenever the TOV flag is set then TOV flag is cleared and wait for another overflown of timer. Here's my code in C though I not sure because I haven't understand how to handle each bit in register yet and I don't know how t simulate it in proteus.

#include <avr/io.h>
int main(void)
{
    TOV1 = 0; // clear timer 1 overflown flag 
    DDRD = 0xFF; // set port D as output
    TCCR1B = 0b00000001; // using internal I/O clock with prescaler 1 
    while(1){
        if (TOV1 = 1){
            PORTD ^= (1<<PORTD0); // toggle bit 0 on port D
            TOV1++; // clear TOV by adding 1 to TOV
        }
    }
}

Best Answer

I see a few things awry here...

1. Assignment instead of compare?

if (TOV1 = 1){

...probably should be...

if (TOV1 == 1){

https://stackoverflow.com/questions/3817246/assignment-and-comparison

  1. TOV1 treated as a register when it is really a bit in the TIFR1 register.

TOV1 = 0;

...should probably be...

TIFR1 |= (1<<TOV1);

(according to the datasheet, the flag is cleared by writing a 1 bit to it)

...and...

if (TOV1 == 1)

...should probably be...

if (TIFR1 & (1<<TOV1) )

2. I don't think you can clear a bit by adding 1 to it

TOV1++; // clear TOV by adding 1 to TOV

...should probably be...

TIFR1 |= (1<<TOV1); // clear TOV bit`

(according to the datasheet, the flag is cleared by writing a 1 bit to it)

3. Better way to toggle a bit

If you really want to toggle a GPIO pin, the PIN register is probably what you want. So...

PORTD ^= (1<<PORTD0); // toggle bit 0 on port D

...would be better as...

PIND = (1<<PORTD0); // toggle bit 0 on port D

You can Read more about this in the datasheet...

13.2.2 Toggling the Pin

Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction can be used to toggle one single bit in a port.