The short story here is that I'm trying to use an Arduino Uno's (ATMega328) Timer1 to send some pulses of a known length through pin 10.
I'm ~90% sure that the timer code is correct, but it seems to be impacting other code in really weird and inexplicable ways. I've read a fair chunk of the ATMega328 datasheet, I've done some Googling, and I've tried two different Arduino Uno boards, but I've been unable to figure out why it's happening.
The problem: The code below continually prints out the "4" on the serial port. It never increments. And its driving me mad. Even if my Timer1 code is wrong, I haven't been able to identify any way that it might be impacting code in loop().
Known so far: If I remove the "TCCR1B |= _BV(CS11);" code from loop() then the serial output increments as expected. But how can this line impact any other code? My googles have left me empty.
Am I missing something obvious?
void setup() {
Serial.begin(230400);
// Stop Timer1
TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10));
// Want non-inverting fast-pwm mode where TOP=ICR1
// Non-inverting (COM1x[1:0] to 0x3)
TCCR1A |= _BV(COM1B1);
TCCR1A &= ~(_BV(COM1A1) | _BV(COM1A0) | _BV(COM1B0));
// Fast PWM where TOP=ICR1 (WGM1[3:0] = 0xE)
TCCR1B |= _BV(WGM13) | _BV(WGM12);
TCCR1A |= _BV(WGM11);
TCCR1A &= ~_BV(WGM10);
// Enable the interrupts
TIMSK1 |= _BV(ICIE1) | _BV(OCIE1B);
TIMSK1 &= ~_BV(OCIE1A);
TCNT1 = 0x00; // starting value
ICR1 = 0xFFFF; // ending value
OCR1B = 0x8FFF;
}
void loop() {
int pulseMilliseconds = 3;
while (true) {
pulseMilliseconds = pulseMilliseconds + 1;
TCCR1B |= _BV(CS11); // start timer with clk/8 prescaler
Serial.println(pulseMilliseconds);
delay(1000);
}
}
SIGNAL(TIMER1_COMPB_vect) {
}
(Note, this is a minimal codeset that replicates the issue that I'm seeing with the full codeset)