Hardware Reference
In-Depth Information
Serial.write (rxBuffer, nBytes);
Serial.println();
}
int transferSPI(int txBytes) {
cli(); // Turn global interrupts off
SPCR |= 0b00010000; // Set SPI master
DDRB |= 0b00101100; // MOSI SCK SS output
DDRB &= 0b11101111; // MISO Input
PORTB &= 0b11111011; // Turn the slave select on
int count = 0;
delay(50); // Wait for connected devices to enter interrupt; 50 is a very safe number
while (count < txBytes) { // Loop until all data has transferred
SPDR = txBuffer[count]; // Begin byte transfer by writing SPDR
while (!(SPSR & (1 << SPIF))); // Wait for transfer to complete
rxBuffer[count] = SPDR; // Read incoming byte
count++;
}
PORTB |= 0b00000100; // Set SS HIGH
}
ISR(SPI_STC_vect) { // SPI interrupt vector
int count = 0;
if (!(PINB & 0b00000100)) { // Enter if SS is LOW
while (!(PINB & 0b00000100)) { // While SS is LOW
while (!(SPSR & (1 << SPIF))); // Wait till data transfer complete
rxBufferSlave[count] = SPDR; // Read SPDR
if (rxBufferSlave[0] == myAddress) {DDRB |= 0b00010000;} // If address matches set MISO to
Output
SPDR = rxBufferSlave[count]; // Write data to send to SPDR
count++;
}
if (rxBufferSlave[0] == myAddress) {flag = true;} // If address matched set LED change flag
initSPI(); // Return to idle connection
}
}
Verifying the Code
For Listing 10-4, you'll need to connect at least two Arduinos together, as per Figure 10-4 . Many more Arduinos
may be used; when more Arduinos are used, the advantage of SABB over SPI becomes apparent. Each connected
device needs a unique address that is set in the code before the sketch is compiled and uploaded. Electrically, the
connections between boards are nearly the same as a standard configuration of SPI. A pull-down resistor is needed
for the data lines to prevent cross talk. An external pull-up resistor may also be added to the chip-select line, though
this is not required. Figure 10-4 shows the specific connections and resistor values.
 
Search WWH ::




Custom Search