Skip to main content
2 of 2
Fixed syntax highlighting, added tags.
VE7JRO
  • 2.5k
  • 19
  • 28
  • 31

SPI communication Problem Arduino

I'm trying to set up SPI communication between two Arduinos (UNO and Mega), I want to read the status of the slave output pin from the master.

I connected a diode to pin 9 of Mega and I wanted to display its state on the virtual terminal of the master (Uno). The problem is that when the LED flashes I do not receive values just at the terminal level but when I hold it to zero or 1 the display is correct. I used another code I found online.

MASTER code

#include <SPI.h>
const byte btn =8;

void setup(void) {

Serial.begin (9600);
pinMode (btn, INPUT_PULLUP);
digitalWrite (SS, HIGH);
SPI.begin ();
SPI.setClockDivider (SPI_CLOCK_DIV8);

}

void loop(void) {

byte Mvalsent,Mvalreceived;
digitalWrite (SS, LOW);
for (int jj=0; jj<255; jj++)
  {
      Mvalsent =jj;
      Mvalreceived =SPI.transfer (Mvalsent);
      Serial.print ("Retou d'etat ");
      Serial.print (Mvalsent);
      Serial.print ("\t ,l'etat de la diode est ");
      Serial.println (Mvalreceived);
      delay (400);
  }
  
  digitalWrite (SS,HIGH);

}

SLAVE Code

#include <SPI.h>
byte state;
const byte led =9; 
volatile boolean process_it;
volatile byte Svalreceived, Svalsent;
int jj=0;
void setup (void)
{
  Serial.begin (9600);
pinMode (led,OUTPUT);
//set MISO pin as output
pinMode (MISO, OUTPUT);
//turn on SPI in slave mode
SPCR |= _BV (SPE);
//get ready for an interrupt
process_it = false;
//now turn on interrupts
SPI.attachInterrupt ();
}
ISR (SPI_STC_vect)
{
  Svalreceived = SPDR;
  process_it =true;
}
void loop (void)
{
 if (process_it)
 {

   digitalWrite (led, LOW);
   state =digitalRead(led);
   SPDR = state;
   Serial.print("l'etat de la diode est: ");
    Serial.println (state);
    delay (400);
    

    process_it =false;
  }
}