Hi,
I need to transmit sensor data from Arduino Nano(Slave) to Arduino Mega(Master).
The Nano should also receive data from the Mega. The master sends the received data back to the slave for monitoring.
Problem:
The received data is always written into the first variable (data) even though it should be written into data2.
I tried serveral things like SS High/Low after each variable and also to write the received data into an array but it always didn't work.
Im looking for example code for sending and receiving multiple variables via SPI.
Thanks you in advance!
//Code Master
#include <SPI.h>
static int data, data2;
void setup() {
// Monitor
Serial.begin(115200);
// SPI Init
digitalWrite(SS,HIGH);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop()
{
transmit();
Serial.print("Receive:\t Data1 = \t");
Serial.print(spi_data);
//same for data2
}
void transfer(){
digitalWrite(SS, LOW);
// Receive Data, send Status
spi_data = SPI.transfer(status);
// Receive Data2, send Status2
spi_data2 = SPI.transfer(status2);
//digitalWrite(SS, HIGH);
}
// Slave Code
void setupSLAVE(){
SPCR |= bit (SPE); //SPI im Slave Modus starten
pinMode(MISO, OUTPUT);
senden = false; //Variablen fuer Buffer vorbereiten
SPI.attachInterrupt(); //SPI Interrupt schalten
}
ISR(SPI_STC_vect)
{
received = SPDR;
senden = true;
}
void check_MASTER(){
if(senden)
{
Serial.print(received);
Serial.print("\t");
sent = data[counter1++];
Serial.println(sent);
SPDR = sent;
senden = false;
if (counter1 == 5){counter1 = 0;}
}
//if (digitalRead(SS) == HIGH){counter1 = 0; }
}