Hardware Reference
In-Depth Information
Table 10-7. SPI Clock-Generation Multipliers
SPCR
SPSR
Divider
SPR1
SPR0
SPI2X
2
0
0
1
4
0
0
0
8
0
1
1
16
0
1
0
32
1
0
1
64
1
0
0
128
1
1
0
The SPSR has two remaining settings left: the SPIF (SPI interrupt flag) and the WCOL (write collision). The SPIF
is set when a serial transmission has completed. It can be cleared in a number of ways, including by reading the SPSR
followed by accessing the SPDR. This feature allows a while loop to execute until the serial transfer is completed. This
prevents you from having to read the SPDR before the byte is actually received, and if you are in a sequence of loops,
it prevents you from writing the SPDR while a transmission is in progress. Should the SPDR be written during a serial
transmission, the WCOL will be set to a logical one. This is not generally preferable, so should be avoided. The WCOL
is cleared in the same fashion as the SPIF.
Let's now see the slave sketch (Listing 10-2).
Listing 10-2. SPI Slave Sketch
byte dataToEcho; // Declare a global variable to be used in interrupt
boolean blink = LOW;
void setup() {
Serial.begin(115200);
DDRB |= 0b00010001; // MISO LED(8) Output
PORTB |= 0b00000100; // Set slave select HIGH
SPCR |= 0b11000000; // Turn SPIE and SPE on
SPSR |= 0b00000000; // Default SPI settings
sei(); // Enable global interrupts
}// End setup
void loop() {
digitalWrite(8, (blink = !blink)); // Blink LED life check
delay(1000);
}// End loop
ISR(SPI_STC_vect) {
cli(); // Turn interrupts off while running sensitive code
while (!(PINB & 0b00000100)) { // Enter while loop if slave select is low
SPDR = dataToEcho; // Load the SPI data register with data to shift out
while (!(SPSR & (1 << SPIF))); // Wait till data transfer is complete
dataToEcho = SPDR; // Read the incomming data. This byte will be sent next interrupt.
}
sei(); // Turn interrupts back on when done
}// End ISR for spi
 
Search WWH ::




Custom Search