Go Down

Topic: Basic SPI Question (beginner) (Read 818 times) previous topic - next topic

theironspud

#5
Dec 02, 2011, 04:12 pm Last Edit: Dec 02, 2011, 05:29 pm by theironspud Reason: 1
I'm playing my "newbie" status card again here, so please bear with me.

Each command and response is two bytes, and I believe that there is only one read per clock cycle allowed.

So, if the command "5600" for temp and "5700" for velocity, would my code need to look like this?

Code: [Select]

if (digitalRead(dateReadyPin) == LOW {
digitalWrite(chipSelectPin, LOW);
SPI.transfer (0x56);
byte temp_high = SPI.transfer (0x00);
byte temp_low = SPI.transfer(0);
digitalWrite(chipSelectPin, HIGH);
}

delay(100);

if (digitalRead(dateReadyPin) == LOW {
digitalWrite(chipSelectPin, LOW);
SPI.transfer (0x57);
byte velocity_high = SPI.transfer (0x00);
byte velocity_low = SPI.transfer (0);
digitalWrite(chipSelectPin, HIGH);
}

Nick Gammon

Almost. See page 12 of the datasheet. It seems to work in 16 bit quantities, so you send 16 bytes (two transfers) and get the reply in the next two transfers. During that second two you could be requesting the next reply and so on.

Also note their comments about "use a clock phase setting of 0 and a clock polarity setting of 1.".

I think you will need this in setup:

Code: [Select]
SPI.setDataMode(SPI_MODE2);

So to get the temperature you send 16 bits and receive 16 bits:

Code: [Select]

digitalWrite(chipSelectPin, LOW);
SPI.transfer (0x56);   // request temperature
SPI.transfer (0x00);
byte temp_high = SPI.transfer (0);  // get temperature
byte temp_low = SPI.transfer(0);
digitalWrite(chipSelectPin, HIGH);


I must say that I don't see 0x5600 as being "get the temperature" but I'll let you work it out from the bit patterns on page 13.

theironspud

I just wanted to share what finally worked.  Thank you for your help Nick.

Code: [Select]

#include <SPI.h>
const int CS = 7;
const int DR = 6;
void setup (){
  Serial.begin(9600);
  SPI.begin();
  pinMode(CS, OUTPUT);
  pinMode(DR, INPUT);
  delay(100);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE3);
  SPI.setClockDivider(SPI_CLOCK_DIV8);
  digitalWrite(CS, HIGH);
  delay(1000); 
}
void loop()


if(digitalRead(DR) == HIGH);
{digitalWrite(CS, LOW);
byte resultHigh = SPI.transfer(0x56);
byte resultLow = SPI.transfer(0x00);

digitalWrite(CS, HIGH);
int dev_high = (int) resultHigh << 8;
int device_ID = dev_high | (int)resultLow;
Serial.println(device_ID);
}
delay(500);
}

Go Up