1 // Simple SPI MASTER example
2 // Counts number of presses on a button connected to D2 (PD2),
3 // and sends the count and the count+100 over SPI.
4 // Uses a mix of Arduino and plain AVR code,
5 // but does not use the Arduino SPI library.
12 Serial.println("Hello from MASTER")
14 // Declare pushbutton as input using the Arduino-way ;)
17 // Set SCK, MOSI and SS as OUTPUTS using the AVR-way ;)
18 DDRB |= (1<<PB5)|(1<<PB3)|(1<<PB2);
19 // Enable SPI, MASTER mode, Fosc/64
20 SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR1);
22 // Make sure SS is pulled HIGH
29 // Loop with no action until button-pressed is
31 if (digitalRead(2)==HIGH)
33 // Wait for button to go back to "idle"
34 while (digitalRead(2)==HIGH) {}
36 count=count+1; // Increment count
38 Serial.print("Count: ");
39 Serial.println(count, DEC);
41 spi_ss_start(); // Set /CS (SS) LOW for transmission
42 spi_rw(count); // Send current count
43 spi_rw(count+100); // and a +100 version ;)
44 spi_ss_end(); // Re-set /CS (SS) HIGH after transmission
49 // Using SS as outgoing /CS pin
52 PORTB &= ~(1<<PB2); // Set SS low using AVR logic ;)
56 PORTB |= (1<<PB2); // Set SS high using AVR logic ;)
59 uint8_t spi_rw( uint8_t d )
61 SPDR = d; // Start the transmission
62 while (!(SPSR & (1<<SPIF))); // Wait for transmission to complete
63 return SPDR; // Return the resulting register content