Go Down

Topic: SPI read write for 32bits data (Read 7 times) previous topic - next topic

Paradigm

Hi, I had a IC that need to be read and write with 32bits data. Can the SPI.h libaray handle 32bits data transfer? How can I declare my variable? Is it long int? Can I program something like SPI.transfer(0xFFFFFFFE);? How about reading?

How can I read a 32bits data from SPI?

Anyone had a file that can read write a 32bits SPI data?

Thanks a lot

dhenry

Sending 8 bits 4 times = sending 32bits.

strykeroz


How can I declare my variable? Is it long int?
That part is up to you.  Depending on where you're receiving this data from, and what it's made up of,  you might declare it as an array of 4 bytes (or characters) or a pair of int, or as a single long.  All will give you 32 bits of data to play with, but when you do the SPI.transfer() for transmit or receive; or ShiftOut() / shiftIn() you'll be sending it in 4 byte-sized pieces (ie 8 bits at a time as dhenry posted above).

How about reading? How can I read a 32bits data from SPI?
The same way, a byte at a time.

What is the IC you're wanting to communicate with?

Cheers ! Geoff
"There is no problem so bad you can't make it worse"
- retired astronaut Chris Hadfield

Tom Carpenter

#3
Nov 19, 2012, 07:36 pm Last Edit: Nov 19, 2012, 07:42 pm by Tom Carpenter Reason: 1
You can use a 'union' to efficiently and quickly convert a long to a series of four bytes or 2 ints or vice versa:
Code: [Select]
#include <SPI.h>

union FourByte{
    unsigned long bit32;
    unsigned int bit16[2];
    unsigned char bit8[4];
};

void setup(){
  SPI.begin();
 
  //save a 32bit value
  unsigned long someValue = 0xFFFFFFFEUL;
  //transmit 32bit value:
  transfer(someValue);
 
  //read 32bit value
  someValue = transfer(0);
 
  //read and write at the same time.
  someValue = transfer(someValue);

  //concatinate ints:
  FourByte bob;
  bob.bit16[0] = 10;
  bob.bit16[1] = 20;
 
  transfer(bob.bit32); //sends 1310730 = 20*65536+10

  //concatinate bytes:
  bob.bit8[0] = 0x1; //1
  bob.bit8[1] = 2; //2
  bob.bit8[2] = 0b11; //3
  bob.bit8[3] = B100; //4
 
  transfer(bob.bit32); //transfers 0x04030201
}

unsigned long transfer(unsigned long value){
  FourByte data = {value};
  for(byte i = 0; i < 4; i++){
    data.bit8[i] = SPI.transfer(data.bit8[i]);
  }
  return data.bit32;
}
~Tom~

Paradigm

Hi,

         If I were to send 4 bytes of data to make up 32bits data transfer, for 0x12345678 to be sent, do I send 0x78 first or do I send 0x12 first?

        As for 4 bytes ready, after reading the 4 bytes, how can I combine them together to become a long int? It is a signed long int

        It is a multimeter IC chip that can measure AC voltage and current.

Go Up