swspi.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "uni_avr_rpi.h"
  2. #ifdef __SWSPI
  3. #include "swspi.h"
  4. #ifdef __RPI
  5. //#define swspi_miso 9
  6. #define swspi_miso 10
  7. #define swspi_mosi 10
  8. #define swspi_sck 11
  9. #define SWSPI_CS 7
  10. #endif //__RPI
  11. #define SWSPI_DEL 0x0f //delay mask (0-3. bit, delay = 1 << DEL [us])
  12. #define SWSPI_POL 0x10 //polarity mask (4. bit, 1=inverted)
  13. #define SWSPI_PHA 0x20 //phase mask (5. bit)
  14. #define SWSPI_DOR 0x40 //data order mask (6. bit, 0=MSB first, 1=LSB first)
  15. #define SWSPI_SCK_UP if (swspi_cfg & SWSPI_POL) GPIO_CLR(swspi_sck); else GPIO_SET(swspi_sck);
  16. #define SWSPI_SCK_DN if (swspi_cfg & SWSPI_POL) GPIO_SET(swspi_sck); else GPIO_CLR(swspi_sck);
  17. unsigned char swspi_miso = 0;
  18. unsigned char swspi_mosi = 0;
  19. unsigned char swspi_sck = 0;
  20. unsigned char swspi_cfg = 0;
  21. void swspi_init(unsigned char miso, unsigned char mosi, unsigned char sck, unsigned char cfg)
  22. {
  23. swspi_miso = miso;
  24. swspi_mosi = mosi;
  25. swspi_sck = sck;
  26. swspi_cfg = cfg;
  27. GPIO_INP(swspi_miso);
  28. GPIO_OUT(swspi_mosi);
  29. GPIO_OUT(swspi_sck);
  30. GPIO_CLR(swspi_mosi);
  31. SWSPI_SCK_DN;
  32. }
  33. void swspi_tx(unsigned char tx)
  34. {
  35. int delay = 1 << (swspi_cfg & SWSPI_DEL));
  36. if (swspi_miso == swspi_mosi) GPIO_OUT(swspi_mosi);
  37. unsigned char i = 0; for (; i < 8; i++)
  38. {
  39. if (tx & 0x80) GPIO_SET(swspi_mosi);
  40. else GPIO_CLR(swspi_mosi);
  41. DELAY(delay);
  42. SWSPI_SCK_UP;
  43. DELAY(delay);
  44. SWSPI_SCK_DN;
  45. tx <<= 1;
  46. }
  47. }
  48. unsigned char swspi_rx()
  49. {
  50. int delay = 1 << (swspi_cfg & SWSPI_DEL));
  51. if (swspi_miso == swspi_mosi) GPIO_OUT(swspi_mosi);
  52. unsigned char rx = 0;
  53. unsigned char i = 0; for (; i < 8; i++)
  54. {
  55. rx <<= 1;
  56. DELAY(delay);
  57. SWSPI_SCK_UP;
  58. DELAY(delay);
  59. rx |= GPIO_GET(swspi_miso)?1:0;
  60. SWSPI_SCK_DN;
  61. }
  62. return rx;
  63. }
  64. unsigned char swspi_txrx(unsigned char tx)
  65. {
  66. int delay = 1 << (swspi_cfg & SWSPI_DEL));
  67. unsigned char rx = 0;
  68. unsigned char i = 0; for (; i < 8; i++)
  69. {
  70. rx <<= 1;
  71. if (tx & 0x80) GPIO_SET(swspi_mosi);
  72. else GPIO_CLR(swspi_mosi);
  73. DELAY(delay);
  74. SWSPI_SCK_UP;
  75. DELAY(delay);
  76. rx |= GPIO_GET(swspi_miso)?1:0;
  77. SWSPI_SCK_DN;
  78. tx <<= 1;
  79. }
  80. return rx;
  81. }
  82. #endif //__SWSPI