From 631204a1feffa8cf3795060370b14dfb9f53f533 Mon Sep 17 00:00:00 2001 From: Camil Staps Date: Tue, 31 Jan 2017 23:15:28 +0100 Subject: WIP --- spi.c | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 spi.c (limited to 'spi.c') diff --git a/spi.c b/spi.c new file mode 100644 index 0000000..f20f732 --- /dev/null +++ b/spi.c @@ -0,0 +1,61 @@ +#include +#include "spi.h" + +void spi_init(void) { + SSPSTAT = 0x40; + SSPCON1 = 0x2a; + SSPADD = 39; // 200 kHz @ 32MHz + + SPI_SDI = 0; + SPI_SCK = 0; + SPI_SDO = 0; + + SPI_SDI_TRIS = 1; + SPI_SCK_TRIS = 0; + SPI_SDO_TRIS = 0; + + SSPCLKPPS = SPI_SCK_PPS_IN; + SSPDATPPS = SPI_SDI_PPS; + + SPI_SCK_PPS_OUT = 0x21; + SPI_SDO_PPS = 0x23; +} + +uint8_t spi_exchange(uint8_t data) { + SSPCON1bits.WCOL = 0; + SSPBUF = data; + while (!SSPSTATbits.BF); + return SSPBUF; +} + +uint8_t spi_exchange_buffer(uint8_t *in, uint8_t buflen, uint8_t *out) { + uint8_t written = 0; + + if (buflen != 0) { + if (in != NULL) { + while (written < buflen) { + if (out == NULL) + spi_exchange(in[written]); + else + out[written] = spi_exchange(in[written]); + written++; + } + } else if (out != NULL) + while (written < buflen) + out[written++] = spi_exchange(DUMMY_DATA); + } + + return written; +} + +inline bool spi_is_buffer_full(void) { + return SSPSTATbits.BF; +} + +inline bool spi_has_write_collision_occured(void) { + return SSPCON1bits.WCOL; +} + +inline void spi_clear_write_collision_status(void) { + SSPCON1bits.WCOL = 0; +} -- cgit v1.2.3