SPI.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #include "pins_arduino.h"
  11. #include "SPI.h"
  12. SPIClass SPI;
  13. void SPIClass::begin() {
  14. // Set SS to high so a connected chip will be "deselected" by default
  15. digitalWrite(SS, HIGH);
  16. // When the SS pin is set as OUTPUT, it can be used as
  17. // a general purpose output port (it doesn't influence
  18. // SPI operations).
  19. pinMode(SS, OUTPUT);
  20. // Warning: if the SS pin ever becomes a LOW INPUT then SPI
  21. // automatically switches to Slave, so the data direction of
  22. // the SS pin MUST be kept as OUTPUT.
  23. SPCR |= _BV(MSTR);
  24. SPCR |= _BV(SPE);
  25. // Set direction register for SCK and MOSI pin.
  26. // MISO pin automatically overrides to INPUT.
  27. // By doing this AFTER enabling SPI, we avoid accidentally
  28. // clocking in a single bit since the lines go directly
  29. // from "input" to SPI control.
  30. // http://code.google.com/p/arduino/issues/detail?id=888
  31. pinMode(SCK, OUTPUT);
  32. pinMode(MOSI, OUTPUT);
  33. }
  34. void SPIClass::end() {
  35. SPCR &= ~_BV(SPE);
  36. }
  37. void SPIClass::setBitOrder(uint8_t bitOrder)
  38. {
  39. if(bitOrder == LSBFIRST) {
  40. SPCR |= _BV(DORD);
  41. } else {
  42. SPCR &= ~(_BV(DORD));
  43. }
  44. }
  45. void SPIClass::setDataMode(uint8_t mode)
  46. {
  47. SPCR = (SPCR & ~SPI_MODE_MASK) | mode;
  48. }
  49. void SPIClass::setClockDivider(uint8_t rate)
  50. {
  51. SPCR = (SPCR & ~SPI_CLOCK_MASK) | (rate & SPI_CLOCK_MASK);
  52. SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((rate >> 2) & SPI_2XCLOCK_MASK);
  53. }