I haven't used ATmega16 for a long time, but in general you can get an interrupt fired at the falling and rising edge, using the output compare interrupt of an AVR. I think with the overflow interrupt as well.
For the first 26 interrupts (13 pulses), you will toggle the desired pin to produce the pwm. You will then hold the pin to 0 in every interrupt, until 1 second is reached. And then 26 pulses counting is starting again and so on.
With ATMega16 ... every PWM signal can generate an interrupt.
13 at falling edge and 13 at rising edge. You can decide which one you want.
Per interrupt you can count the pulses and stop the output after 13.
And you can count on while the output is enabled.
***
An example:
You want 13 pulses with a frequency of 1kHz.
* Then start the output,
* count 13 pulses
* disable the output, but let the timer counter/ continue to interrupt
* count 987 pulses to determin the rest of the second
* then restart the loop
You can run all these short functions within the ISR. And have plenty of processing power remaining for the main loop.
I haven't used ATmega16 for a long time, but in general you can get an interrupt fired at the falling and rising edge, using the output compare interrupt of an AVR. I think with the overflow interrupt as well.
For the first 26 interrupts (13 pulses), you will toggle the desired pin to produce the pwm. You will then hold the pin to 0 in every interrupt, until 1 second is reached. And then 26 pulses counting is starting again and so on.
Ok. But I do not know how to do this. I know how to generate PWM wave on OCR0 pin. What would be the next? It will be continued in generate. But I need only 13 cycles to the Ultrasonic sensor.
SO what I need to do next?
For 40kHz, I need to do prescaling and TCCR0=6C and OCR0 will be 204.
So I will get PWM pulses on OCR0 pin. Now what to do next to have only 13 cycles?
Ok. But I do not know how to do this. I know how to generate PWM wave on OCR0 pin. What would be the next? It will be continued in generate. But I need only 13 cycles to the Ultrasonic sensor.
It was already mentioned that you should use the timer interrupt service to count the amount of interrupts. Reaching 13 events, means 13 pulses on output, isn't it clear ?