SPI Communication Between two Arduino Boards

In this tutorial I am going to brief you on how to establish a communication between two arduino boards through SPI(Serial Peripheral Interface). SPI is also called as 4 wire interface, because it uses four pins to transmit and receive data, they are MISO (Master In Slave Out), MOSI(Master Out Slave In), SCK – This provides the clock signal for data transfer, usually from master to slave. And SS pin- It selects the slave device, it is an active low signal given by Master device. After completing the data transfer with one slave device, the master device pulls up the SS pin to high. In SPI protocol, it is possible to connect more than one slave to a master device. The master device can communicate with any slave connected to the bus at any time, but the slave can communicate only to the master. Whenever the master device wants to send a data to slave, it pulls down the SS Pin and the slave will listen to data. The master device is controlling the clock signal for data transfer, so the slave cannot be able to initiate data transfer.


CIRCUIT DIAGRAM


SPI between two arduino


Master Code

#include <stdlib.h>
#include <SPI.h>

int i=0;
char inData[64];
char k[30];
char inChar;
int valid=0;
int index=0;
#define SCK_PIN  13
#define MISO_PIN 12
#define MOSI_PIN 11
#define SS_PIN   10


void setup()
{
  pinMode(MOSI_PIN, OUTPUT);
  pinMode(MISO_PIN, INPUT);
  pinMode(SCK_PIN, OUTPUT);
  pinMode(SS_PIN, OUTPUT);

  digitalWrite(SS_PIN, HIGH); 

  SPI.begin();
  Serial.begin(9600);
}


void transferAndWait(char what)
{
  SPI.transfer(what);
  delayMicroseconds(20);

void send(char *p)
{
  char c;
  while(*p)
  {
    c=*p++;
    transferAndWait(c);
    delay(20);
  }
}



void loop()
{

  digitalWrite(SS_PIN, LOW);  
  byte numBytesAvailable= Serial.available();


 send("Hello World...\n");


  delay(100);
}



Slave Code


#include <LiquidCrystal.h>
#include <stdlib.h>
#include <SPI.h>

#define SCK_PIN  52
#define MISO_PIN 50
#define MOSI_PIN 51
#define SS_PIN   53  
int i=0;
char k[20],v[20];
int valid=0;
LiquidCrystal lcd(22, 23, 24, 25, 26, 27, 28);
void setup (void)
{
  Serial.begin (9600);  
  pinMode(MOSI_PIN, INPUT);
  pinMode(MISO_PIN, OUTPUT);
  pinMode(SCK_PIN, INPUT);
  pinMode(SS_PIN, INPUT);
  SPCR |= _BV(SPE);
  SPCR != _BV(SPIE);

  SPI.attachInterrupt();

}
ISR (SPI_STC_vect)
{
char c = SPDR;  
if(c=='\n')
{
 lcd.clear();
 Serial.println(k);
lcd.print(k);
  i=0;
}
else if(c!='\n')
{
  k[i]=c;
  i++;
}
}


void loop (void)
{
 
while(1);
}



Comments