D:/DRISSI/arduino-0022/arduino-0022/libraries/SPI/SPI.cpp
00001 /*
00002  * Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
00003  * SPI Master library for arduino.
00004  *
00005  * This file is free software; you can redistribute it and/or modify
00006  * it under the terms of either the GNU General Public License version 2
00007  * or the GNU Lesser General Public License version 2.1, both as
00008  * published by the Free Software Foundation.
00009  */
00010 
00011 #include "pins_arduino.h"
00012 #include "SPI.h"
00013 
00014 SPIClass SPI;
00015 
00016 void SPIClass::begin() {
00017   // Set direction register for SCK and MOSI pin.
00018   // MISO pin automatically overrides to INPUT.
00019   // When the SS pin is set as OUTPUT, it can be used as
00020   // a general purpose output port (it doesn't influence
00021   // SPI operations).
00022 
00023   pinMode(SCK, OUTPUT);
00024   pinMode(MOSI, OUTPUT);
00025   pinMode(SS, OUTPUT);
00026   
00027   digitalWrite(SCK, LOW);
00028   digitalWrite(MOSI, LOW);
00029   digitalWrite(SS, HIGH);
00030 
00031   // Warning: if the SS pin ever becomes a LOW INPUT then SPI 
00032   // automatically switches to Slave, so the data direction of 
00033   // the SS pin MUST be kept as OUTPUT.
00034   SPCR |= _BV(MSTR);
00035   SPCR |= _BV(SPE);
00036 }
00037 
00038 void SPIClass::end() {
00039   SPCR &= ~_BV(SPE);
00040 }
00041 
00042 void SPIClass::setBitOrder(uint8_t bitOrder)
00043 {
00044   if(bitOrder == LSBFIRST) {
00045     SPCR |= _BV(DORD);
00046   } else {
00047     SPCR &= ~(_BV(DORD));
00048   }
00049 }
00050 
00051 void SPIClass::setDataMode(uint8_t mode)
00052 {
00053   SPCR = (SPCR & ~SPI_MODE_MASK) | mode;
00054 }
00055 
00056 void SPIClass::setClockDivider(uint8_t rate)
00057 {
00058   SPCR = (SPCR & ~SPI_CLOCK_MASK) | (rate & SPI_CLOCK_MASK);
00059   SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((rate >> 2) & SPI_2XCLOCK_MASK);
00060 }
00061