i have this simple code that i use for generating a square wave signal of 125 KHz on pin 9 using Timer1 in the "Clear Timer on Compare Match (CTC) Mode". I also use Timer1 Compare Match A interrupt for toggling pin 7 of PORTD.
void setup() {
pinMode(9, OUTPUT);
pinMode(7, OUTPUT);
TCNT1 = 0;
TCCR1A = 0;
TCCR1B = 0;
OCR1A = 7;
TIMSK1 = _BV(OCIE1A);
TCCR1A = _BV(COM1A0);
TCCR1B = _BV(CS11) | _BV(WGM12);
}
void loop() {
}
ISR(TIMER1_COMPA_vect)
{
PORTD = PORTD ^ 128;
}
It happens that
The 125KHz waveform on pin 7 is delayed by 1us with respect to the waveform of pin 9. I think that is related to the time that the microcontroller takes to "entering" the interrupt function and toggling the PORTD pin (1us are 16 clock cycle of the 16MHz master clock).
Sometimes the waveform on pin 7 (the one generated inside the interrupt service routine) has some "gaps". For example, this is the waveform acquired with my scope:
Why this strange behaviour happens?
Thank you