SoftSpi.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #ifndef _SPI_H_INCLUDED
  11. #define _SPI_H_INCLUDED
  12. #define MOSI 0
  13. #define MISO 1
  14. #define SCK 2
  15. #define SS 3
  16. //pointless defines
  17. #define SPI_CLOCK_DIV4 0x00
  18. #define SPI_CLOCK_DIV16 0x01
  19. #define SPI_CLOCK_DIV64 0x02
  20. #define SPI_CLOCK_DIV128 0x03
  21. #define SPI_CLOCK_DIV2 0x04
  22. #define SPI_CLOCK_DIV8 0x05
  23. #define SPI_CLOCK_DIV32 0x06
  24. //#define SPI_CLOCK_DIV64 0x07
  25. #define SPI_MODE0 0x00
  26. #define SPI_MODE1 0x04
  27. #define SPI_MODE2 0x08
  28. #define SPI_MODE3 0x0C
  29. #define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR
  30. #define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR
  31. #define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR
  32. class SoftSpi {
  33. public:
  34. inline static byte transfer(byte _data);
  35. // SPI Configuration methods
  36. inline static void attachInterrupt();
  37. inline static void detachInterrupt(); // Default
  38. static void begin(); // Default
  39. static void end();
  40. static void setBitOrder(uint8_t);
  41. static void setDataMode(uint8_t);
  42. static void setClockDivider(uint8_t);
  43. };
  44. extern SoftSpi SPI;
  45. byte SoftSpi::transfer(byte data) {
  46. unsigned char bit = 0;
  47. for(bit = 0; bit < 8; bit++) // Loop through 8 bits
  48. {
  49. if(data & 0x80) digitalWrite(MOSI,HIGH); // If bit(7) of "data" is high
  50. else digitalWrite(MOSI,LOW); // if bit(7) of "data" is low
  51. digitalWrite(SCK,HIGH); // Serial Clock Rising Edge
  52. data <<= 1; // Shift "data" to the left by one bit
  53. if(digitalRead(MISO)==HIGH) data |= 0x01; // If bit of slave data is high
  54. else data &= ~0x01; // if bit of slave data is low
  55. digitalWrite(SCK,LOW); // Serial Clock Falling Edge
  56. }
  57. return data; // Returns shifted data in value
  58. }
  59. void SoftSpi::attachInterrupt() {
  60. }
  61. void SoftSpi::detachInterrupt() {
  62. }
  63. #endif