I'm trying to send 2 byte size int values between two Arduino Unos using SPI.
I made two sketches, one for Master and one for Slave
but it works in a weird way.
Master receives two bytes but one from previous count and one from current count.
The first and second bytes from Slave are in reverse order.
There may be some synchronization problem but I cannot figure out.
I added some Serial.print stuff to check the behavior.
Even when I removed the Serial.print stuff, it did not work.
Here is the sketch for Master
#include <SPI.h>
void setup (void) {
  SPI.begin ();
  Serial.begin(9600);
}
void loop (void) {
  uint8_t count1, count2;
  int count;
  
  SPI.beginTransaction( SPISettings(1000000, MSBFIRST, SPI_MODE0) );
  digitalWrite(SS, LOW); // select slave
  count1 = SPI.transfer(0); // MSB
  delayMicroseconds (20);
  count2 = SPI.transfer(0); // LSB
  count = (count1 << 8) | count2;
  
  Serial.print("1st byte : ");
  Serial.println(count1);
  Serial.print("2nd byte : ");
  Serial.println(count2);
  Serial.print("* slave count : ");
  Serial.println(count);
  digitalWrite(SS, HIGH); // de-select slave
  SPI.endTransaction();
    
  delay(1000);
}
Here is the sketch for Slave.
#include <SPI.h>
int count = 250;
const int TRANSMIT_BYTES = 2;
volatile boolean transmit_start;
int transmit_data;
volatile int transmit_count = 0;
void setup () {
  pinMode(MISO, OUTPUT);
  pinMode(MOSI, INPUT);
  pinMode(SCK, INPUT);
  pinMode(SS, INPUT);
  SPI.setClockDivider(SPI_CLOCK_DIV16);
  SPCR |= _BV(SPE);       // SPI enable
  SPCR &= ~_BV(MSTR);     // Slave mode enable
  SPCR |= _BV(SPIE);      // enable interrupt
  Serial.begin(9600);
  transmit_start = false;
}
ISR (SPI_STC_vect) {
  if(!transmit_start){
    transmit_start = true;
    transmit_data = count;
    uint8_t d = (transmit_data >> 8) & 0xFF;
    SPDR = d;
    transmit_count++;
    Serial.print("1st byte : ");
    Serial.println(d);
  }
  else{
    uint8_t d = transmit_data & 0xFF;
    SPDR = d;
    transmit_count++;
    if(transmit_count == TRANSMIT_BYTES){
      transmit_start = false;
      transmit_count = 0;
    }
    Serial.print("2nd byte : ");
    Serial.println(d);
  }
}
void loop (){
  count++;
  Serial.println(String("* slave count : ") + count);
  delay(1000);
}
Thanks in advance.

