SPI programming

Hi, I am trying to program for a pressure sensor which uses the SPI protocol. However, it seems like that my code doesn't run properly. Can some one help me with this? I appreciate that a lot!!!

Here is the datasheet

#include <SPI.h> // include the SPI library
const int cs = 10;
const byte sample = 10000011;
const byte resend = 01010000;

void setup(){
  pinMode(cs,OUTPUT);
  Serial.begin(9600);//initialize the serial monitor 
  Serial.println("Initializing the force monitor");
  delay(50);//give the numatac some time to setup
  SPI.begin();//begin SPI trasaction
  digitalWrite(cs,HIGH);
  }


void loop(){
  //Set up SPI bus
  //set the clock speed to be 5 Mhz, most significant byte first, and data trasfer mode 0
  SPI.beginTransaction(SPISettings(4400000,MSBFIRST,SPI_MODE0));
    uint8_t MSBbyte, LSBbyte;
    digitalWrite(cs,LOW);
    SPI.transfer(sample);
    SPI.transfer(sample);
    digitalWrite(cs,HIGH);
    delayMicroseconds(50);
    digitalWrite(cs,LOW);
    MSBbyte = SPI.transfer(resend);
    LSBbyte = SPI.transfer(resend);
    SPI.endTransaction();
    digitalWrite(cs,HIGH);

    MSBbyte = unsigned(MSBbyte)>> 1;
    LSBbyte = unsigned(LSBbyte)>> 3;
    LSBbyte <<= 3;

   unsigned int rawdata = MSBbyte*256 + LSBbyte;
   unsigned int pressure = unsigned(rawdata) >> 3;
    Serial.println(pressure);

by the way, I just want to get the fluid pressure which is Pdc.

While listening to the responses from the NumaTac the host should write 0x0001 to the MOSI lines to avoid errors.

You don't seem to be doing that.

I added this line "SPI.transfer(0x0001)" either before or after the 50 microsecond delay, but it still doesn't work. Could you please give some some advice? I am beginner of SPI protocol, and I have no idea what to do next. :slightly_frowning_face: Thanks.

    digitalWrite(cs,LOW);
    SPI.transfer(sample);
    SPI.transfer(sample);
    digitalWrite(cs,HIGH);
    delayMicroseconds(50);
    SPI.transfer(0x0001);
    digitalWrite(cs,LOW);
    MSBbyte = SPI.transfer(resend);
    LSBbyte = SPI.transfer(resend);
    SPI.endTransaction();
    digitalWrite(cs,HIGH);

I think you want:

    digitalWrite(cs,LOW);
    SPI.transfer(0x83);  // Sample Command for Channel 1
    SPI.transfer(0x00);  // Eight bits of Don't Care
    digitalWrite(cs,HIGH);
    delayMicroseconds(50);
    digitalWrite(cs,LOW);
    MSBbyte = SPI.transfer(0x00);
    LSBbyte = SPI.transfer(0x01);
    digitalWrite(cs,HIGH);
    SPI.endTransaction();

Note: You can't write binary constants as a string of 0's and 1's. What you wrote was "sample = Ten Million and Eleven" and "resend = Octal 1010000" (that's decimal 266,240). The leading '0' makes it an octal (base eight) constant. Naturally neither of them will work as expected. The way(s) to write a binary constant:

const byte sample = B10000011;  // Arduino-form binary constant
const byte resend = 0b01010000;  // Non-standard C binary constant

Most programmers write binary constants in HEX.