SPI.transfer hangs up

I can't get SPI.transfer to work on my Arduino Mega 2560. Sketch hangs up on the function call. I understand SS pin on port needs to be set as an output, even though I am using other pins for chip select.

#include <SPI.h> // include the SPI library
#define SPI_MISO 50 // PB3 SPI MISO
#define SPI_MOSI 51 // PB2 SPI MOSI
#define SPI_CLK 52 // PB1 SPI CLK
#define SPI_SS 53 // PB0 SPI SS (not used but port needs this)
#define DAC_CS 11 // PB5 DAC CS
#define LED1GRN 13 // PB7 LED

void setup() {
pinMode(SPI_SS,OUTPUT); // SPI I/O port
pinMode(SPI_MISO,INPUT);
pinMode(SPI_MOSI,OUTPUT);
pinMode(SPI_CLK,OUTPUT);
pinMode(DAC_CS,OUTPUT);
pinMode(LED1GRN,OUTPUT);
digitalWrite(SPI_SS,HIGH);
digitalWrite(DAC_CS,HIGH);
digitalWrite(SPI_MISO,HIGH);
}
//--------------------------------------------------------------------------
void loop() {

word DAC_value = 0x8FFF;

// initialize SPI:
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV32);
SPI.setDataMode(SPI_MODE0); //SCK idle low, latch data rising edge
SPI.begin;

digitalWrite(DAC_CS,LOW);

SPI.transfer(0x20); // DAC Command byte <--- code seems to hang here!
digitalWrite(LED1GRN, HIGH); // set the LED on <--- we never make it here, LED stays off

SPI.transfer(highByte(DAC_value));
SPI.transfer(lowByte(DAC_value));
digitalWrite(DAC_CS,HIGH);
}

The SPI init code should be in setup(), I don't think that would be the problem though.

How do you know the code never gets to that line? Maybe the LED wiring is wrong. WHat happens of you use D13 and the on-board LED?


Rob

I have an LED blink in the main (loop) that works fine until I add SPI.transfer- moving the LED on instruction, I traced it down to that.
If I instead use shiftout, everything works. But I need SPI to access other peripherals. I also tried reading data instead of writes data=SPI.transfer(0x00) and it hangs too.
Not sure what else to try :frowning:

Did you move the setup code into setup()?

Without looking into the library code I don't know if it matters, but there's no need to have it there.


Rob

prairiemystic:

...

SPI.begin;
...

That doesn't look right. Where are the brackets?

Also don't do that in loop, do it in setup like Graynomad said.

It is the missing brackets on SPI.begin() that cause it to hang at run time.
Thanks everyone for your help.