Reading and generating square waves at the same time.

I re wrote the code using timer interrupts and it is good up to 2.5khz with verry little jitter but above 2.5khz it stops outputing. It is getting better and thanks for all the help.

Here is the current code. Im sure its full or errors as its the first time i have used interrputs.

#
#include <FreqPeriodCounter.h>

const byte Speed_output = 7;      // the output pin to speedometer
const byte Speed_input = 3; 
const byte counterInterrupt = 1; // = pin 3

unsigned long hz = 0 ;
double x = 1;        // Correction Factor of Output to input
 

FreqPeriodCounter counter(Speed_input, micros,0);

void setup() 
{
  pinMode (Speed_input,INPUT_PULLUP);  // Pull up input pin 3 to 5 volts 
  pinMode(Speed_output, OUTPUT);      // Output pin 7 to sink current from speedometer
   
  attachInterrupt(counterInterrupt, counterISR, CHANGE);
  
cli();//stop interrupts
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  
  // set compare match register for ?hz increments
  OCR1A = 65535; // = (16*10^6) / (64*hz) - 1 (must be <65536)
  TCCR1B |= (1 << WGM12);// turn on CTC mode
  TCCR1B |= (1 << CS11) | (1 << CS10);  // Set CS11 and CS10 bits for 64 prescaler
  TIMSK1 |= (1 << OCIE1A);// enable timer compare interrupt
sei();//allow interrupts

}

ISR(TIMER1_COMPA_vect){//timer1 interrupt Hz/2 toggles output
  PIND = 0b10000000; // toggle output pin D7 
 }

void loop()
{ 
  
  if(counter.ready()) hz=counter.hertz();
      
  OCR1A = (((F_CPU/(64*hz))-1)/2*x);

}


void counterISR()
{ counter.poll();
}