I have a master and a slave (both are arduino UNO) connected through SPI connected. I want to transmit a character to the slave and receive true or false to the master. The transmission is working perfectly. If I send '2'
, slave is receiving '2'
. When I try to transmit an integer from slave to master, the master is always receiving some arbitrary number like 128 or 255.
Master Code:
void setup() {
Serial.begin(9600);
Serial.println("Master");
digitalWrite(SS,HIGH);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop() {
digitalWrite(SS,LOW); // Slave select to low
received1 = SPI.transfer(test); // test is a variable which is '2'. The data received by master is stored in received1 variable which is char.
Serial.println(received1);
digitalWrite(SS,HIGH);
}
Slave code:
void setup() {
Serial.begin(9600);
Serial.println("Slave");
pinMode(MISO,OUTPUT);
SPCR |= _BV(SPE);
process = false;
SPI.attachInterrupt();
}
ISR(SPI_STC_vect){
received = SPDR; // the data received by slave is slored in **received** variable(the variable is char type)
Serial.println(received);
process = true;
}
void loop() {
if(process){
SPDR = jj; // Updating SPDR to send data from slave. jj is char type
process = false;
}
}
1 Answer 1
I have found a solution for this problem in a blog.
Link: http://www.gammon.com.au/forum/?id=10892
I modified my master code and got my desired result.
Master code:
byte transferAndWait (const byte what)
{
byte a = SPI.transfer (what);
delayMicroseconds (2000);
return a;
} // end of transferAndWait
void loop() {
digitalWrite(SS,LOW);
transferAndWait (10);
received1 = transferAndWait (11);
digitalWrite(SS,HIGH);
Serial.println(received1);
}
The response will be "collected" next time through the loop. That's why we need to keep a dummy transferAndWait()
function first and then the result of that transfer will be stored in received1
variable.
-
Please accept your own answer if it solved your problem, otherwise Stack Exchange throws it up from time to time as an unsolved question.2017年08月07日 09:25:53 +00:00Commented Aug 7, 2017 at 9:25
Explore related questions
See similar questions with these tags.
process
, is not here. Is it volatile? Also do you realize that SPDR on slave must be set before the master starts transmission?process
. It's aboolean
variable which will be true when something is received by slave.