2020-03-29 12:12:42 +02:00

63 lines
1.3 KiB
C

#include <assert.h>
#include <stddef.h>
#include "nrf.h"
#include "driver.h"
#include "spi.h"
static inline int spi_transfer(uint32_t t);
int spi_open(const struct driver *drv)
{
assert(NULL != drv);
struct spi *this = (struct spi *)drv->dev;
NRF_SPI0->ENABLE = 0;
NRF_SPI0->PSELSCK = this->sck_pin;
NRF_SPI0->PSELMOSI = this->mosi_pin;
NRF_SPI0->PSELMISO = this->miso_pin;
NRF_SPI0->FREQUENCY = SPI_FREQUENCY_FREQUENCY_M8;
NRF_SPI0->CONFIG = (0x03 << 1); //Sample on trailing edge of clock, shift serial data on leading edge, SCK polarity Active low
NRF_SPI0->EVENTS_READY = 0;
NRF_SPI0->ENABLE = (SPI_ENABLE_ENABLE_Enabled << SPI_ENABLE_ENABLE_Pos);
return 0;
}
int spi_close(const struct driver *drv)
{
NRF_SPI0->ENABLE = 0;
return 0;
}
int spi_write(const struct driver *drv, const char *buffer, unsigned int len)
{
assert(NULL != buffer);
//FIXME: missing CS handling
for(unsigned int i = 0; i < len; i++) {
spi_transfer(buffer[i]);
}
//FIXME: missing CS handling
return len;
}
static inline int spi_transfer(uint32_t t)
{
volatile uint32_t r;
NRF_SPI0->EVENTS_READY = 0; // ready
NRF_SPI0->TXD = t; // out
while(NRF_SPI0->EVENTS_READY == 0) {
}
r = NRF_SPI0->RXD; // in
return (int)r;
}