spi.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Copyright 2018 Massdrop Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include "arm_atsam_protocol.h"
  15. Srdata_t srdata;
  16. void SPI_WriteSRData(void)
  17. {
  18. uint16_t timeout;
  19. SC2_RCLCK_LO;
  20. timeout = 50000;
  21. while (!(SCSPI->SPI.INTFLAG.bit.DRE) && --timeout) { DBGC(DC_SPI_WRITE_DRE); }
  22. SCSPI->SPI.DATA.bit.DATA = srdata.reg & 0xFF; //Shift in bits 7-0
  23. timeout = 50000;
  24. while (!(SCSPI->SPI.INTFLAG.bit.TXC) && --timeout) { DBGC(DC_SPI_WRITE_TXC_1); }
  25. SCSPI->SPI.DATA.bit.DATA = (srdata.reg >> 8) & 0xFF; //Shift in bits 15-8
  26. timeout = 50000;
  27. while (!(SCSPI->SPI.INTFLAG.bit.TXC) && --timeout) { DBGC(DC_SPI_WRITE_TXC_2); }
  28. SC2_RCLCK_HI;
  29. }
  30. void SPI_Init(void)
  31. {
  32. uint32_t timeout;
  33. DBGC(DC_SPI_INIT_BEGIN);
  34. CLK_set_spi_freq(CHAN_SERCOM_SPI, FREQ_SPI_DEFAULT);
  35. PORT->Group[0].PMUX[6].bit.PMUXE = 2;
  36. PORT->Group[0].PMUX[6].bit.PMUXO = 2;
  37. PORT->Group[0].PINCFG[12].bit.PMUXEN = 1;
  38. PORT->Group[0].PINCFG[13].bit.PMUXEN = 1;
  39. //Configure Shift Registers
  40. SC2_DIRSET;
  41. SC2_RCLCK_HI;
  42. SC2_OE_DIS;
  43. SCSPI->SPI.CTRLA.bit.DORD = 1;
  44. SCSPI->SPI.CTRLA.bit.CPOL = 1;
  45. SCSPI->SPI.CTRLA.bit.CPHA = 1;
  46. SCSPI->SPI.CTRLA.bit.DIPO = 3;
  47. SCSPI->SPI.CTRLA.bit.MODE = 3; //master
  48. SCSPI->SPI.CTRLA.bit.ENABLE = 1;
  49. timeout = 50000;
  50. while (SCSPI->SPI.SYNCBUSY.bit.ENABLE && timeout--) { DBGC(DC_SPI_SYNC_ENABLING); }
  51. srdata.reg = 0;
  52. srdata.bit.HUB_CONNECT = 0;
  53. srdata.bit.HUB_RESET_N = 0;
  54. srdata.bit.S_UP = 0;
  55. srdata.bit.E_UP_N = 1;
  56. srdata.bit.S_DN1 = 1;
  57. srdata.bit.E_DN1_N = 1;
  58. srdata.bit.E_VBUS_1 = 0;
  59. srdata.bit.E_VBUS_2 = 0;
  60. srdata.bit.SRC_1 = 1;
  61. srdata.bit.SRC_2 = 1;
  62. srdata.bit.IRST = 1;
  63. srdata.bit.SDB_N = 0;
  64. SPI_WriteSRData();
  65. //Enable register output
  66. SC2_OE_ENA;
  67. DBGC(DC_SPI_INIT_COMPLETE);
  68. }