0
votes

I'm trying to establish a full-duplex SPI communication between RaspberryPI B+ (Master) and Arduino Uno (slave).

Master-side code:

#include<sys/ioctl.h>
#include<linux/spi/spidev.h>
#include<fcntl.h>
#include<cstring>
#include<iostream>
#include<unistd.h>

using namespace std;

int fd;
unsigned int val;
unsigned int result;

int spiTxRx(unsigned int txDat);

int main(void){
    fd = open("/dev/spidev0.0",O_RDWR);
    unsigned int speed = 1000000;
    ioctl(fd,SPI_IOC_WR_MAX_SPEED_HZ,&speed);
    int ret = 0;
    while(ret <=5){
        ret++;      
        cout<<"input:";
        cin>>val;
        result=spiTxRx(val);
        cout<<result<<endl;
        usleep(10);
    }
    close(fd);
}

int spiTxRx(unsigned int txDat){
    unsigned char rxDat;
    struct spi_ioc_transfer spi;
    memset(&spi,0,sizeof(spi));

    spi.tx_buf = (unsigned long) &txDat;
    spi.rx_buf = (unsigned long) &rxDat;
    spi.len = 1;
    ioctl (fd, SPI_IOC_MESSAGE(1), &spi);

    return rxDat;
}

Slave-Side code

byte clr;
int x = 0;
int readInput;
void setup (void){

  Serial.begin (9600);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode. SPCR determine Arduino SPI settings
  SPCR |= _BV(SPE);
  clr = SPSR;
  clr = SPDR;  
  delay(10);
}

void loop (void){

  if ((SPSR & _BV(SPIF)) !=0){ //if byte has been received 
      readInput = SPDR;
      if (readInput == 7){
        x++;
        SPDR = x;
      }
  }
} 

So, simply I want that if I send throw MOSI line an input (in this case 7), Arduino increment var x and reply me with value of x.

But my outputs are looks like these:

init: x = 0;
(1st input)
Master send 7, Slave add x (so, x=1) and send me back unusual value
(2nd input)
Master send 7, Slave add x (x=2) and send me back 1 (previous value of x)
(3rd input)
Master send 7, slave add x (x=3) and send me back 2 (previous value of x)
(Nth input)
Master send 7, slave add x (x = k) and send me back k-1

In other words, if I send 7, Arduino increment x, loop in while line and send me back the same input value. If I send again a value, Arduino reply me with right response.

Somebody can help me?

1

1 Answers

0
votes

I found a solution about my problem.

Discrepancy between sent and received message was caused by Arduino SPI Data Register (SPDR). SPDR is defined by an 8 bits shift register and an 8 bits receive buffer. When Master send a byte, it is stored in the receive buffer and byte in shift register is sent back to master. So we need to send another message to get a right response back.