Hi, this is my first post on this forum. Im not sure how to add code to the post other than copy/paste.
I am trying to have a slave device send 3 bytes of data to a master device (both Arduinos).
The first byte of data in the packet always comes out wrong and sometimes the first byte of the second packet as well. I'm not sure why, but i think the Serial monitor may be the issue?
Below is my Master code, slave code and the Master output on the Serial monitor.
#include <SPI.h>
/************************************************MASTER TEST FILE: USED TO FIGURE OUT HOW TO SEND 3 BYTES TO THE MASTER FROM THE SLAVE******************************/
int del= 15;
byte b[3];
unsigned long message = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV128);
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
pinMode(MISO, INPUT);
pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH); // ensure SS stays high for now
}
void loop()
{
// put your main code here, to run repeatedly:
digitalWrite(SS, LOW); //TURN SPI TRANSFER ON
b[2] = SPI.transfer(0x50); //0x50
delay(del);
Serial.println(b[2], HEX);
b[1] = SPI.transfer(0x02); //0x00
delay(del);
Serial.println(b[1], HEX);
b[0] = SPI.transfer(0x03); //0x00
delay(del);
Serial.println(b[0], HEX);
digitalWrite(SS, HIGH); //TURN SPI TRANSFER OFF
}
/SLAVE CODE*********/
int messageCounter = 0;
volatile byte command = 0;
String display[9] = {"0x000000", "0x400000", "0x100000", "0x002000", "0x000100", "0x000080", "0x000040", "0x000008", "0x000004"};
long int myMessages[9] = {0x123456, 0x020000, 0x030000, 0x042000, 0x050100, 0x060080, 0x070040, 0x080008, 0x090004}; //TEST MESSAGES
//long int myMessages[9] = {0x000000, 0x400000, 0x100000, 0x002000, 0x000100, 0x000080, 0x000040, 0x000008, 0x000004}; //REAL MESSAGES
byte b[3];
/**********************************************************Slave Receive Function***************************************************/
byte SPI_SlaveReceive(void)
{
/* Wait for reception complete */
while(!(SPSR & (1<<SPIF)))
;
/* Return Data Register */
return SPDR;
}
void setup()
{
pinMode(MISO, OUTPUT);
pinMode(SS, INPUT);
SPCR |= _BV(SPE); //turn on SPI in slave mode
//SPCR |= _BV(SPIE);
}
void loop()
{
b[2] = (myMessages[messageCounter] >> 16); //MSB
b[1] = (myMessages[messageCounter] >> 8);
b[0] = (myMessages[messageCounter]); //LSB
//spi sending happens here
if (digitalRead (SS) == LOW)
{
command = SPI_SlaveReceive();
if (command == 0x50)
{
for (int i=2; i>=0; i--)
{
SPDR = b[i];
while(!(SPSR & (1<<SPIF)));
}
}
else
{
//do nothing
}
}
else
{
// do nothing
}
}


