SPI stops functioning once Serial or Delay are used

Using a Mega2560 Writing my first SPI library to become more familiar with the protocol. Was having a hard time as it appeared that the Arduino was refusing to send any data, oscilloscope seemed to confirm this was the voltages would not fluctuate. As a sanity check I tried the Arduino example, which worked and I was able to see the data on the oscilloscope. I compared my code to the example and from trial and error I found that the SPI library was not working when delay or Serial.print was added to the code (was using them for debugging). Changing the delay from 1000 to 1 and slowing down the bus seems to resolve this, increasing delay or bus speed causes it to fail again. What can I do to work around this?

#include <SPI.h>

void setup() {
  Serial.begin(9600);

  SPI.begin();

  delay(100);
}

int i = 0;

void loop() {
  SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0)); // Using MCP2515 at 10 Mhz
  SPI.transfer(i++ % 255); // Changing data to help show code is working on scope
  SPI.endTransaction();
  delay(1); // Delay of 1 breaks SPI
}

I'm a bit confused. You wrote that "Changing the delay from 1000 to 1 and slowing down the bus seems to resolve this", which I take to mean that a delay of 1 mSec makes it appear to work for you. But in your code you say that "Delay of 1 breaks SPI". Which is it?

I have since figured out it was an issue with the scope not being turned to a low enough sec/div so it wasn't trigging like I was expecting. The no delay was just making the bus more active and therefor easier to see. Appears to be working now.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.