lpc176x: Add support for SPI

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
This commit is contained in:
Kevin O'Connor 2018-07-18 09:15:53 -04:00
parent acefe26e0f
commit e2b4b1616f
4 changed files with 91 additions and 0 deletions

View File

@ -7,6 +7,7 @@ config LPC_SELECT
default y
select HAVE_GPIO
select HAVE_GPIO_ADC
select HAVE_GPIO_SPI
select HAVE_USER_INTERFACE
config BOARD_DIRECTORY

View File

@ -14,6 +14,7 @@ CFLAGS_klipper.elf += --specs=nano.specs --specs=nosys.specs
# Add source files
src-y += lpc176x/main.c lpc176x/timer.c lpc176x/gpio.c lpc176x/i2c.c
src-$(CONFIG_HAVE_GPIO_SPI) += lpc176x/spi.c
src-y += generic/crc16_ccitt.c generic/alloc.c
src-y += generic/armcm_irq.c generic/timer_irq.c
src-y += ../lib/lpc176x/device/system_LPC17xx.c

View File

@ -27,4 +27,12 @@ uint32_t gpio_adc_sample(struct gpio_adc g);
uint16_t gpio_adc_read(struct gpio_adc g);
void gpio_adc_cancel_sample(struct gpio_adc g);
struct spi_config {
uint32_t cr0, cpsr;
};
struct spi_config spi_setup(uint32_t bus, uint8_t mode, uint32_t rate);
void spi_prepare(struct spi_config config);
void spi_transfer(struct spi_config config, uint8_t receive_data
, uint8_t len, uint8_t *data);
#endif // gpio.h

81
src/lpc176x/spi.c Normal file
View File

@ -0,0 +1,81 @@
// SPI support on lpc176x
//
// Copyright (C) 2018 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include "LPC17xx.h" // LPC_SSP0
#include "command.h" // shutdown
#include "gpio.h" // spi_setup
#include "internal.h" // gpio_peripheral
#include "sched.h" // sched_shutdown
static void
spi_init(void)
{
static int have_run_init;
if (have_run_init)
return;
have_run_init = 1;
// Configure SCK0, MISO0, MOSI0 pins
gpio_peripheral(0, 15, 2, 0);
gpio_peripheral(0, 17, 2, 0);
gpio_peripheral(0, 18, 2, 0);
// Set initial registers
LPC_SSP0->CR0 = 0x07;
LPC_SSP0->CPSR = 254;
LPC_SSP0->CR1 = 1<<1;
}
struct spi_config
spi_setup(uint32_t bus, uint8_t mode, uint32_t rate)
{
if (bus || mode > 3)
shutdown("Invalid spi_setup parameters");
// Make sure bus is enabled
spi_init();
// Setup clock rate and mode
struct spi_config res = {0, 0};
uint32_t pclk = SystemCoreClock / 4;
uint32_t div = DIV_ROUND_UP(pclk/2, rate) << 1;
res.cpsr = div < 2 ? 2 : (div > 254 ? 254 : div);
res.cr0 = 0x07 | (mode << 6);
return res;
}
void
spi_prepare(struct spi_config config)
{
LPC_SSP0->CR0 = config.cr0;
LPC_SSP0->CPSR = config.cpsr;
}
void
spi_transfer(struct spi_config config, uint8_t receive_data
, uint8_t len, uint8_t *data)
{
if (receive_data) {
while (len--) {
LPC_SSP0->DR = *data;
// wait for read data to be ready
while (!(LPC_SSP0->SR & (1<<2)))
;
// get data
*data++ = LPC_SSP0->DR;
}
} else {
while (len--) {
LPC_SSP0->DR = *data++;
// wait for read data to be ready
while (!(LPC_SSP0->SR & (1<<2)))
;
// read data (to clear receive fifo)
LPC_SSP0->DR;
}
}
}