Advertisement
Mukmin039

SPI

Jul 21st, 2022
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.18 KB | None | 0 0
  1.  
  2. #include "spi1.h"
  3. #include <xc.h>
  4.  
  5. typedef struct {
  6.     uint8_t con1;
  7.     uint8_t stat;
  8.     uint8_t add;
  9.     uint8_t operation;
  10. } spi1_configuration_t;
  11.  
  12. //con1 == SSPxCON1, stat == SSPxSTAT, add == SSPxADD, operation == Master/Slave
  13. static const spi1_configuration_t spi1_configuration[] = {  
  14.     { 0xa, 0x40, 0x27, 0 },
  15.     { 0x2, 0x40, 0x4, 0 }
  16. };
  17.  
  18. void SPI1_Initialize(void)
  19. {
  20.     //SPI setup
  21.     SSP1STAT = 0x40;
  22.     SSP1CON1 = 0x02;
  23.     SSP1ADD = 0x04;
  24.     TRISCbits.TRISC3 = 0;
  25.     ANSELCbits.ANSC3 =0;
  26.     TRISCbits.TRISC4 = 1;
  27.     ANSELCbits.ANSC4 =0;
  28.     TRISCbits.TRISC5 = 0;
  29.     ANSELCbits.ANSC5 =0;
  30.    
  31.     //SSP1CON1bits.SSPEN = 0;
  32.     SSP1CON1bits.SSPEN = 1;
  33.    
  34. }
  35.  
  36. bool SPI1_Open(spi1_modes_t spi1UniqueConfiguration)
  37. {
  38.     if(!SSP1CON1bits.SSPEN)
  39.     {
  40.         SSP1STAT = spi1_configuration[spi1UniqueConfiguration].stat;
  41.         SSP1CON1 = spi1_configuration[spi1UniqueConfiguration].con1;
  42.         SSP1CON2 = 0x00;
  43.         SSP1ADD  = spi1_configuration[spi1UniqueConfiguration].add;
  44.         TRISCbits.TRISC3 = spi1_configuration[spi1UniqueConfiguration].operation;
  45.         SSP1CON1bits.SSPEN = 1;
  46.         return true;
  47.     }
  48.     return false;
  49. }
  50.  
  51. void SPI1_Close(void)
  52. {
  53.     SSP1CON1bits.SSPEN = 0;
  54. }
  55.  
  56. uint8_t SPI1_ExchangeByte(uint8_t data)
  57. {
  58.     SSP1BUF = data;
  59.      while(!PIR1bits.SSP1IF);
  60. //    while(!SSP1STATbits.BF);
  61.     //while (!SSP1STAT &  _SSP1STAT_BF_MASK);
  62.     PIR1bits.SSP1IF = 0;
  63.     return SSP1BUF;
  64. }
  65.  
  66. void SPI1_ExchangeBlock(void *block, size_t blockSize)
  67. {
  68.     uint8_t *data = block;
  69.     while(blockSize--)
  70.     {
  71.         SSP1BUF = *data;
  72.         while(!PIR1bits.SSP1IF);
  73.         PIR1bits.SSP1IF = 0;
  74.         *data++ = SSP1BUF;
  75.     }
  76. }
  77.  
  78. // Half Duplex SPI Functions
  79. void SPI1_WriteBlock(void *block, size_t blockSize)
  80. {
  81.     uint8_t *data = block;
  82.     while(blockSize--)
  83.     {
  84.         SPI1_ExchangeByte(*data++);
  85.     }
  86. }
  87.  
  88. void SPI1_ReadBlock(void *block, size_t blockSize)
  89. {
  90.     uint8_t *data = block;
  91.     while(blockSize--)
  92.     {
  93.         *data++ = SPI1_ExchangeByte(0);
  94.     }
  95. }
  96.  
  97. void SPI1_WriteByte(uint8_t byte)
  98. {
  99.     SSP1BUF = byte;
  100. }
  101.  
  102. uint8_t SPI1_ReadByte(void)
  103. {
  104.     return SSP1BUF;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement