(Solved) SPI.begin interfering with Timer 2

For my current project, I am going to attempt to make a fairly low-speed, DAC-controlled frequency generator. For that I want to use a Timer2 interrupt to control when to send signals to the DAC. For now, I’m just trying to use the interrupt to flash an LED to prove that it works.

Here is the code that works:

#include <SPI.h>

void setup()
  //SPI.setClockDivider( SPI_CLOCK_DIV2 );
  pinMode( 13, OUTPUT );
  set_timer_2(7, 255);

void loop()

void set_timer_2(uint8_t prescaler_setting, uint8_t counter_top)
  // Compare Outputs disconnected
  // Waveform Generation Mode: CTC Top OCR1A
  TCCR2A = _BV(WGM21);
  OCR2A = counter_top;
  TCCR2B = prescaler_setting;
  // timer started after prescaler set.

volatile uint8_t  sine_index = 0;
  sine_index = !sine_index;
  digitalWrite( 13, sine_index );
  /*uint16_t command_word = (1<<13) | (1<<12); //set shutdown and gain bits.
  command_word |= ( lookup_DAC_sine(sine_index)<<2 );
  digitalWrite( SLAVE_SELECT, LOW );
  SPI.transfer( highByte(command_word) );
  SPI.transfer( lowByte(command_word) );
  digitalWrite( SLAVE_SELECT, HIGH );
  if( sine_index==FULL_WAVE )

The problem is that when I uncomment SPI.begin(), the interrupt no longer works (the LED stops flashing). This is problematic because I want to use Timer 2 to time signals to an SPI DAC, so I need the SPI bus.

I’ve skimmed the SPI section of the datasheet, and it makes no mention of Timer 2. And the TImer 2 section makes no mention of SPI that I could find. I opened up the SPI.cpp source file in the Arduino libraries and could find nothing modifying timer 2.

Why are these two modules interfering with each other? Is there some way around this, or do I have to move my interrupt to Timer1?

SPI and Timer2 actually have nothing to do with each other, but pin 13 is the SPI clock signal, so pick another pin. Don't pick pins 11 or 12 either, they are the SPI MOSI and MISO signals, respectively.

Doh! Of course. I changed it to pin 9 and it works.

What a dopey mistake to make. :stuck_out_tongue: Thank you.