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
loop
should be insetup
. Otherwise youloop
code is constantly resetting the counter, back to zero (TCNT0 = 0;)