]> git.defcon.no Git - AVRduinoSPI-example/blob - master/master.ino
Storing some SPI example code
[AVRduinoSPI-example] / master / master.ino
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.
6
7 long int count=1;
8
9 void setup()
10 {
11 Serial.begin(115200);
12 Serial.println("Hello from MASTER")
13
14 // Declare pushbutton as input using the Arduino-way ;)
15 pinMode(2, INPUT);
16
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);
21
22 // Make sure SS is pulled HIGH
23 spi_ss_end();
24
25 }
26
27 void loop()
28 {
29 // Loop with no action until button-pressed is
30 // detected
31 if (digitalRead(2)==HIGH)
32 {
33 // Wait for button to go back to "idle"
34 while (digitalRead(2)==HIGH) {}
35
36 count=count+1; // Increment count
37
38 Serial.print("Count: ");
39 Serial.println(count, DEC);
40
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
45
46 }
47 }
48
49 // Using SS as outgoing /CS pin
50 void spi_ss_start()
51 {
52 PORTB &= ~(1<<PB2); // Set SS low using AVR logic ;)
53 }
54 void spi_ss_end()
55 {
56 PORTB |= (1<<PB2); // Set SS high using AVR logic ;)
57 }
58
59 uint8_t spi_rw( uint8_t d )
60 {
61 SPDR = d; // Start the transmission
62 while (!(SPSR & (1<<SPIF))); // Wait for transmission to complete
63 return SPDR; // Return the resulting register content
64 }
65