Hello,
I'm trying to setup 2 Arduinos communicating using SPI. One is the master and the other the slave unit. I've boiled down the code to about as simple as I can but about 20% of the time the data transmission is missed on the slave. The 2 units are connected directly SPI to SPI. The code just loops 0 to 20 over and over and sends the current value to the other unit. I have to believe that SPI protocol is intended to be much more consistent than the results I'm seeing so I'm hoping someone here can help me determine why some transmissions are missed. The LED attached to pins 5 on each unit is just a visual indicator that makes it easy to spot a missed transmission. When working the LEDs will flash briefly at the same time. When a transfer is missed the slave LED will stay lit until the next transfer is received. It rarely misses more than 1 transfer in a row.
Any suggestions?
The Master code is:
#include <Arduino.h>
#include <SPI.h>
int led=5;
int c = 0;
// Initialize SPI Master Device
void spi_init_master () {
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,INPUT);
pinMode(13,OUTPUT);
SPCR = (1<<MSTR) | (1<<SPE);
}
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin (led) as an output.
pinMode(5,OUTPUT);
Serial.begin(115200);
Serial.println("Entering Setup");
spi_init_master();
}
void sendViaSPI(int intData){
digitalWrite(10,LOW); //Pull SS low
digitalWrite(5,HIGH); //Turn on indicator LED
delay(200); //Pause for 200 ms
Serial.println("Sent: " + String(c)); //Print current value
SPDR = c; //start transfer using SPI
while(!(SPSR & (1<<SPIF))); //wait until transfer is complete before continuing
digitalWrite(10,HIGH); //Pull SS back HIGH
digitalWrite(5,LOW); //Turn off indicator LED
}
// the loop function runs over and over again forever
void loop() {
sendViaSPI(c); //go transfer the value
delay(1000); //pause for 1 second before repeating
c++;
if (c>20){
c=0;
}
}
The slave code is:
#include <SPI.h>
int led = 5;
// Initialize SPI Slave Device
void spi_init_slave (void)
{
pinMode(10,INPUT);
pinMode(11,INPUT);
pinMode(12,OUTPUT);
pinMode(13,INPUT);
SPCR = (1<<SPE);
}
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin (led) as an output.
pinMode(led, OUTPUT);
pinMode(5,OUTPUT);
Serial.begin(115200);
spi_init_slave();
Serial.println("Slave Started");
}
// the loop function runs over and over again forever
void loop() {
if (!digitalRead(10)){
digitalWrite(5,HIGH);
while(!(SPSR & (1<<SPIF)));
byte rx = SPDR;
Serial.println("Received: " + String(rx));
digitalWrite(5,LOW);
delay(200);
}
}