Generate 1khz square signal with Arduino Mega I want to generate a 1khz square signal with an Arduino Mega.
I have read the MCU contains several timers.
What i want to do is to configure one of this timers.
My first question is: Is there a way to automatically control an output pin from the timer, without having to execute any line of code in my arduino program ? Look at my code: i need to write a line in ISR(TIMER1_OVF_vect). Some MCU can do that but i did not find any information about it on documentation. (Some pins are connected on timer outputs, by hardware conception).
My second question is: What is wrong on my calculation on my code ?
I want 1khz and i get 990Hz
Here is what i've done:

Arduino Mega runs at 16Mhz = 16000Khz
I have set a /8 prescaler, so timer's frequency is 8000Khz
The frequency should by divide by two because i have 2 states (HIGH and LOW): 4000Khz
The interupt is fired when the counter reach 65536. So if i load 65536-1000 in TCNT1, the timer should count 1000 times in order to fire the interupt. So my frequency is 4000khz/1000 = 1khz.

What is wrong ?
Thanks a lot
void setup() {
  pinMode(14,OUTPUT);
  
  noInterrupts();
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 65536 - 1000; 
  TCCR1B |= (1 &lt;&lt; CS11);    // Prescaler clock / 8
  TIMSK1 |= (1 &lt;&lt; TOIE1);
  interrupts();
}

ISR(TIMER1_OVF_vect)
{
  TCNT1 = 65536 - 1000;
  digitalWrite(14, digitalRead(14) ^ 1);
}

void loop() {

}
My first question is: Is there a way to automatically control an output pin from the timer, without having to execute any line of code in my arduino program ?

Yes. It's called PWM with a 50% duty cycle.
You need to read up on 19. Output Compare Modulator (OCM1C0A) in the datasheet.

My second question is: What is wrong on my calculation on my code ? I want 1khz and i get 990Hz

You have to take into account the number of CPU cycles it takes to start executing your ISR. There's a short bit of code before your code is run that preserves any used registers on the stack and allocates any room needed for local variables. That takes time, and must be calculated into your timing factor.