spi1.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // This file is part of parrocchetto.
  2. // parrocchetto is free software: you can redistribute it and/or modify
  3. // it under the terms of the GNU General Public License as published by
  4. // the Free Software Foundation, either version 3 of the License, or
  5. // (at your option) any later version.
  6. // parrocchetto is distributed in the hope that it will be useful,
  7. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. // GNU General Public License for more details.
  10. // You should have received a copy of the GNU General Public License
  11. // along with parrocchetto. If not, see <http://www.gnu.org/licenses/>.
  12. #include "spi1.h"
  13. #include <xc.h>
  14. #include <stdint.h>
  15. void spi1_init(void)
  16. {
  17. IFS0bits.SPI1IF = 0; // Clear the Interrupt flag
  18. IEC0bits.SPI1IE = 0; // Disable the interrupt
  19. SPI1CON1bits.DISSCK = 0; // Internal serial clock is enabled
  20. SPI1CON1bits.DISSDO = 0; // SDOx pin is controlled by the module
  21. SPI1CON1bits.MODE16 = 0; // Communication is 8 bit
  22. SPI1CON1bits.MSTEN = 1; // Master mode enabled
  23. SPI1CON1bits.SMP = 0; // Input data is sampled at the middle of data output time
  24. SPI1CON1bits.CKE = 0; // Serial output data changes on transition from
  25. // Idle clock state to active clock state
  26. SPI1CON1bits.CKP = 0; // Idle state for clock is a low level;
  27. // active state is a high level
  28. SPI1CON1bits.PPRE = 3; // Primary clock prescale 1:1
  29. SPI1CON1bits.SPRE = 6; // Secondary clock prescale 2:1
  30. // PPS
  31. RPINR20bits.SDI1R = 6; // SDI1: RP6
  32. RPOR3bits.RP7R = 9; // ~SS1: RP7
  33. RPOR4bits.RP8R = 7; // SDO1: RP8
  34. RPOR4bits.RP9R = 8; // SCK1: RP9
  35. spi1_end(); // Put ~SS1 high
  36. SPI1STATbits.SPIEN = 1;
  37. }
  38. inline uint8_t spi1_write(uint8_t x)
  39. {
  40. SPI1BUF = x;
  41. while(!SPI1STATbits.SPIRBF);
  42. //asm("nop");
  43. //asm("nop");
  44. //asm("nop");
  45. //asm("nop");
  46. return SPI1BUF;
  47. }
  48. inline void spi1_writebuf(const uint8_t* buf, uint16_t buf_size)
  49. {
  50. uint16_t i;
  51. for(i = 0; i < buf_size; ++i)
  52. spi1_write(buf[i]);
  53. }
  54. inline void spi1_readbuf(uint8_t* buf, uint16_t buf_size)
  55. {
  56. uint16_t i;
  57. for(i = 0; i < buf_size; ++i)
  58. buf[i] = spi1_read();
  59. }