Hardware Reference
In-Depth Information
SPCR |= 0b01010000; // This is the SPI control register. SPE (bit 6) enables SPI, and MSTR (bit 4)
sets device as master
SPSR |= 0b00000000; // Default SPI settings and interrupts
}
void loop() {
if (Serial.available() > 0) {
int count = 0;
delay(50); // Allow serial to complete receiving
while (Serial.available() > 0) {
txBuffer[count] = Serial.read(); // Dump serial buffer into the txBuffer
count++;
}
PORTB &= 0b11111011; // Turn the slave select on
transferSPI(count);
PORTB |= 0b00000100; // Turn the slave select off
}
// Blink code
PORTB |= 0b00000001;
delay(1000); // Wait for a second
PORTB &= 0b11111110;
delay(1000); // Wait for a second
}
int transferSPI(int txBytes) {
int count = 0;
while (count < txBytes) {
SPDR = txBuffer[count]; // Writing to the register begins SPI transfer
while (!(SPSR & (1 << SPIF))); // While until transfer complete
rxBuffer[count] = SPDR; // Read newly received byte
count++;
}
displayBuffer(count);
}
int displayBuffer(int nBytes) { // Write txBuffer and rxBuffer to the screen
Serial.write (txBuffer, nBytes);
Serial.println();
Serial.write (rxBuffer, nBytes);
Serial.println();
}
Verifying the Code
To use the master code from the second example, connect it to an Arduino running the slave code from the first
example. This will be in the normal fashion, straight through, as per Figure 10-2 . Verification of code consists of
running a serial connection and sending data. The data will be echoed in the same fashion as the first example. This
code implements one major difference: it takes all incoming serial data and loads it into an array so that the SPI
transmission can be completed in series with greater efficiency. The SS line goes low and stays low until all data in the
txBuffer has been sent and the rxBuffer is filled.
 
Search WWH ::




Custom Search