Thursday, September 18, 2014

Communication betweeen Arduinos using SPI


This example show how to communicate between two Arduino Uno using SPI. The connection is shown here:


On Master side, any data received from Serial (PC), it will be sent to slave Arduino using SPI. And data received from slave will be sent to Serial (PC).

SPIMaster.ino
#include <SPI.h>
byte dataOut;
byte dataIn;

int pinSS = 10;  //Slave Select, active LOW

void setup(){
  Serial.begin(115200);  //link to PC
  
  pinMode(pinSS, OUTPUT);
  digitalWrite(pinSS, HIGH);
  SPI.begin();
}

void loop(){
  while(Serial.available() > 0){
    dataOut = Serial.read();
    dataIn = spiWriteAndRead(dataOut);
    Serial.write(dataIn);
  }
}

byte spiWriteAndRead(byte dout){
  byte din;
  digitalWrite(pinSS, LOW);
  delay(1);
  din = SPI.transfer(dout);
  digitalWrite(pinSS, HIGH);
  return din;
}

On Slave side, any data received from SPI will be sent to Serial (PC) and echo back to master Arduino in next round of transmission.

SPISlave.ino
byte dataEcho;  //echo back input data in next round
byte dataToPC;  //send input data to PC

void setup() {
    Serial.begin(115200);  //link to PC
    
    //The Port B Data Direction Register
    DDRB  |= 0b00010000; 
   //The Port B 
    PORTB |= 0b00000100;
    
    //SPI Control Register
    SPCR  |= 0b11000000;
    //SPI status register
    SPSR  |= 0b00000000;
    
    dataEcho = 0;
    dataToPC = 0;
    
    sei();
}

void loop() {
  
  if(dataToPC != 0){
    Serial.write(dataToPC);
    dataToPC = 0;
  }

}

ISR(SPI_STC_vect){
  cli();
  
  //while SS Low
  while(!(PINB & 0b00000100)){
    SPDR = dataEcho;
    
    //wait SPI transfer complete
    while(!(SPSR & (1 << SPIF)));
    
    dataEcho = SPDR;  //send back in next round
  }
  sei();
}

1 comment:

  1. Hello, i have a doubt. I have an arduino uno, and i need add 2 shields to my project. One is an wifi shield and the other is an datalogger shield. When i put the 3, the wifi shield does not work, but if i remove datalogger shield, then wifi shield works fine. I need use SPI protocol? I think yes, but i don't know how. Any ideas? Thank you so much!

    ReplyDelete