unsigned long waveHz = 100000;
unsigned int exacttime, numofovf;
volatile unsigned int timeovf;
unsigned long waveTime;
void setup() {
pinMode(2, OUTPUT);
waveTime = (1.0/(waveHz*2.0))*16000000;
numofovf = waveTime/65536;
exacttime = waveTime-(numofovf*65536UL);
if(exacttime>38){
exacttime = exacttime-38;
} else {
exacttime = 65535-38+exacttime;
numofovf = numofovf - 1;
}
cli();
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = exacttime;
TCCR1B |= (1 << CS10);
TIMSK1 |= (1 << OCIE1A);
TIMSK1 |= (1 << TOIE1);
sei();
}
void loop() {
}
ISR(TIMER1_COMPA_vect){
if(timeovf == numofovf){
TCNT1 = 0;
timeovf = 0;
PORTD ^= bit(2);
}
}
ISR(TIMER1_OVF_vect){
timeovf++;
}
Wouldn't be easier to just use PWM mode with 50% duty cycle to generate the square wave?