]> git.defcon.no Git - AVRduinoSPI-example/blob - slave/slave.ino
Storing some SPI example code
[AVRduinoSPI-example] / slave / slave.ino
1 // Interrupt-driven SPI SLAVE example
2 // Recieves bytes over SPI and stuffs them in
3 // a sort-of-circular-buffer that is printed to Serial.
4 // Uses a mix of Arduino and plain AVR code,
5 // but does not use the Arduino SPI library.
6
7 #include <avr/interrupt.h>
8
9 volatile uint8_t buffer[16];
10 volatile uint8_t bptr;
11
12
13 void setup()
14 {
15 Serial.begin(115200);
16 Serial.println("Hello from SLAVE")
17
18 // A nice little debug/status pin, set as OUTPUT using the Arduino-way ;)
19 pinMode(7, OUTPUT);
20
21 // Make sure our buffer-pointer starts at the first buffer byte (pos 0)
22 bptr = 0;
23
24 // Set MISO as OUTPUT using the AVR-way ;)
25 DDRB=(1<<DDB4);
26 // Enable SPI (default Slave) and enable SPI interrupts
27 SPCR=(1<<SPE)|(1<<SPIE);
28
29 // Activate interrupts
30 sei();
31 }
32
33 void loop()
34 {
35 // In the main loop, simply output the buffer contents, over and over again..
36 Serial.print("b ");
37 for ( uint8_t i = 0; i <= 15; i++ )
38 {
39 Serial.print(i);
40 Serial.print(" = ");
41 Serial.print(buffer[i]);
42 Serial.print(" ");
43 }
44 Serial.println(" ... ");
45 delay(500);
46 }
47
48 // The ISR for SPI Serial Transfer Complete gets triggered
49 // on each byte transferred.
50 ISR(SPI_STC_vect)
51 {
52 // Put data in buffer, increment buffer pointer, wrap around on end.
53 buffer[bptr] = spi_read();
54 bptr++;
55 if (bptr > 15) bptr = 0;
56 }
57
58 uint8_t spi_read( ){
59 // Getting the transferred byte is as imple as reading the Data Register
60 // each time a byte has completed transfer. This and the ISR, needs to be
61 // quick, so that the next byte does not overwrite the current one.
62
63 // Sending is done by setting the data register before reading ...
64 SPDR = 0;
65 uint8_t d = SPDR;
66
67 // Let's add some fun "things happen because of transfers"...
68 if ( d == 45 ) digitalWrite(7, ( !digitalRead(7) ) );
69
70 return d;
71 }
72
73
74