How to sample incoming 600khz pin and divide it by 4 and generate low frequency signal at output pin of arduino I am trying to divide a incoming high frequency signal 600kHz by 4 and output wave at arduino MEGA2560 digital pin.


The input to arduino comes from incremental Encoder which is connected to motor that runs at 9000 rpm and the generates 1024 pulses per rotation.
I am trying to downsample the frequency I am getting from arduino to 250kHz or less.
I tried following approaches :

a. I counted the rising edge of the incoming wave and a interrupt is triggered as number of rising edge reaches certain value and ISR toggle an output pin.
b. I tried to get hardware counter work at T0 pin but I was not able to hit ISR when the count has reached specific value.


The problem with approach 1 is: As my frequency of incoming wave increases the output wave starts missing some pulses and generates one half cycle for 6/8/10 pulses of incoming wave. It should actually generate one half cycle for 4 pulses.

Here is approach 2 code:

#define outPin1 10
volatile short encoder = 4;

void setup ()
{
   pinMode (outPin1, OUTPUT);
   Serial.begin(9600);
   cli();
   // reset Timer 0
   TCCR0A = 0;
   TCCR0B = 0;

 }  // end of setup

 ISR(TIMER0_COMPA_vect)
 {
     digitalWrite(outPin1, !digitalRead(outPin1));

 }

 void loop ()
 {
    TCNT0 = 0;      //counter to zero

    // set compare match register to desired timer count:
   OCR0A = encoder;
    // turn on CTC mode:

   bitSet(TCCR0A, WGM01);
   // Timer 0 - counts events on pin D4

  bitSet(TIMSK0, OCIE0A);    // interrupt on Timer 0 CTC
   // start Timer 0
  // External clock source on T0 pin (D4). Clock on rising edge.

   bitSet(TCCR0B, CS02);
   bitSet(TCCR0B, CS01);
   bitSet(TCCR0B, CS00);
}


Please someone help me out with this issue
This is probably too fast to have have software involved in the loop.
You should try to use a hardware-only solution. Note the Arduino timers
should be usable as hardware frequency dividers:


configure a timer to be clocked off the input signal, so that it
behaves like a counter.
configure it for delivering a PWM output with a period of 4 timer
clock cycles and a duty cycle of 50%.


You may try this, but beware I have not tested it:



void setup()
{
    // Configure Timer 5 as a frequency divider:
    //   input: digital pin 47 = PL2 = T5
    //   ouput: digital pin 46 = PL3 = OC5A
    DDRL  |= _BV(PL3);    // set pin PL3 as output
    TCCR5A = 0;           // undo the Arduino core's configuration
    TCCR5B = 0;
    ICR5   = 4 - 1;       // period = 4 timer clock cycles
    OCR5A  = 2 - 1;       // output HIGH for 2 timer clock cycles
    TCCR5A = _BV(COM5A1)  // non-inverting PWM on pin OC5A
           | _BV(WGM51);  // mode 14: fast PWM, TOP = ICR5
    TCCR5B = _BV(WGM52)
           | _BV(WGM53)
           | _BV(CS50)    // clock on rising edges of T5
           | _BV(CS51)
           | _BV(CS52);
}

void loop(){}