I am trying to use 328's Timer1 to create a custom wave form. I started an earlier thread and was suggested to use TimerOne library which I tried but wasn't fast enough to generate the waveform, which is not a PWM type output but more complex.
After reading TimerOne code and some reading of 328's data sheet, I started setting registers to see if I can first generate a 50% duty cycle waves for my understanding. Here is my code that I thought should generate a 4.096ms LOW and then 4.096ms HIGH wave with 8.192ms period:
#define ABout 8
void setup() {
digitalWrite(ABout,LOW);
pinMode(ABout,OUTPUT);
TIMSK1 = _BV(TOIE1);// Enable interrupt
TCCR1B = _BV(WGM13);
TCCR1A = 0;
ICR1=65535U;
TCCR1B=B00010001;
}
ISR(TIMER1_OVF_vect)
{
PORTB=PINB^B1;
}
So in my theory if I set 65535 as TOP and with no prescalar, it counts 65536 CPU cycles, at 16MHz, so 65536/16=4096us between each logic level flip. But my logic analyzer captured consistent 8192us time between each logic level flip. I tried different TOP count values and prescalar value and always ended up twice as long as I thought. I looked at TimerOne.h and found a factor of 2 was included. I wonder why. If you count say 65536 CPU cycles at 16MHz, and then flip output, then between flips timing is 4096us, why twice?