I am using the ATMega32u4 to generate a pulse at 1 kHz. I am using Timer 3, which is a 16-bit timer and using a prescaler of 1, so I have a 0.0625uS resolution. The good news is that this is working, I can control the frequency and pulse length of the square wave. The issue is that I noticed the pulse always seems to be 1uS off.
If I set a period of 1000uS, and a pulse of 500uS, the oscilloscope shows a period of 1001uS and a pulse of 501uS.
If I set a period of 100uS, and pulse of 10uS, the oscilloscope shows a period of 101uS, and a pulse of 11uS.
If the Timer had an error percentage, then both the period and pulse should be off by the same percentage, but there are always off by the same 1uS length. I assume I am doing something wrong, so I have posted my code below.
const int pin1 = 4;
void setup() {
//Set pin to output
pinMode(pin1, OUTPUT);
// Reset Timer 3 Control Register to 0
TCCR3A = 0;
// Set prescaler to 1
TCCR3B &= ~(1 << CS32); //0
TCCR3B &= ~(1 << CS31); //0
TCCR3B |= (1 << CS30); //1
//Reset Timer 3 and set compare value
TCNT3 = 0;
// Enable Timer 3 compare interrupt A and B
TIMSK3 |= (1 << OCIE3B);
TIMSK3 |= (1 << OCIE3A);
//Enable global interrupts
sei();
//Set Refresh Rate
OCR3A = 1000;
OCR3B = 100 / 0.0625;
}
void loop() {
delay(100);
}
ISR(TIMER3_COMPA_vect) {
PORTD &= ~_BV(pin1); //LOW
OCR3A = 160;
}
ISR(TIMER3_COMPB_vect) {
TCNT3 = 0;
PORTD |= _BV(pin1); //HIGH
}


100 / 0.0625instead of simply1600? – hcheung May 13 '20 at 01:29