• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
3  * SPI Master library for arduino.
4  *
5  * This file is free software; you can redistribute it and/or modify
6  * it under the terms of either the GNU General Public License version 2
7  * or the GNU Lesser General Public License version 2.1, both as
8  * published by the Free Software Foundation.
9  */
10 
11 #ifndef _SPI_H_INCLUDED
12 #define _SPI_H_INCLUDED
13 
14 #include <stdio.h>
15 #include <WProgram.h>
16 #include <avr/pgmspace.h>
17 
18 #define SPI_CLOCK_DIV4 0x00
19 #define SPI_CLOCK_DIV16 0x01
20 #define SPI_CLOCK_DIV64 0x02
21 #define SPI_CLOCK_DIV128 0x03
22 #define SPI_CLOCK_DIV2 0x04
23 #define SPI_CLOCK_DIV8 0x05
24 #define SPI_CLOCK_DIV32 0x06
25 #define SPI_CLOCK_DIV64 0x07
26 
27 #define SPI_MODE0 0x00
28 #define SPI_MODE1 0x04
29 #define SPI_MODE2 0x08
30 #define SPI_MODE3 0x0C
31 
32 #define SPI_MODE_MASK 0x0C  // CPOL = bit 3, CPHA = bit 2 on SPCR
33 #define SPI_CLOCK_MASK 0x03  // SPR1 = bit 1, SPR0 = bit 0 on SPCR
34 #define SPI_2XCLOCK_MASK 0x01  // SPI2X = bit 0 on SPSR
35 
36 class SPIClass {
37 public:
38   inline static byte transfer(byte _data);
39 
40   // SPI Configuration methods
41 
42   inline static void attachInterrupt();
43   inline static void detachInterrupt(); // Default
44 
45   static void begin(); // Default
46   static void end();
47 
48   static void setBitOrder(uint8_t);
49   static void setDataMode(uint8_t);
50   static void setClockDivider(uint8_t);
51 };
52 
53 extern SPIClass SPI;
54 
transfer(byte _data)55 byte SPIClass::transfer(byte _data) {
56   SPDR = _data;
57   while (!(SPSR & _BV(SPIF)))
58     ;
59   return SPDR;
60 }
61 
attachInterrupt()62 void SPIClass::attachInterrupt() {
63   SPCR |= _BV(SPIE);
64 }
65 
detachInterrupt()66 void SPIClass::detachInterrupt() {
67   SPCR &= ~_BV(SPIE);
68 }
69 
70 #endif
71