This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

How to properly use SPI with nrf connect sdk?

Hello, I couldn't find any examples of SPI usage with nrf connect sdk, where can I find them?

At the beginning I want to do pretty simple thing - just send array of bytes through SPI, I know how to do it with arduino, but I don't know how to do it wih nrf.

In arduino my code would looks like this:

std::array<uint8_t, 34> arr = {
    0x02, 0x00, 0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x20, 
    0x57, 0x4f, 0x52, 0x4c, 0x44, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00
};

void sendDummyData() {
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
  digitalWrite(SS, LOW);
  for (const uint8_t b : arr) {
    SPI.transfer(b);
  }
  digitalWrite(SS, HIGH);
  SPI.endTransaction();
}

Now, let's back to nrf.

I created overlay file with name nrf52840dk_nrf52840.overlay in boards directory with content:

&spi0 {
    status = "ok";
	sck-pin = <4>;
	mosi-pin = <6>;
	miso-pin = <11>;
	ss-pin = <28>;
	spi-max-frequency = <1000000>;
};

I enabled SPI in prj.conf:

# Enable SPI
CONFIG_SPI=y
CONFIG_SPI_0=y
CONFIG_SPI_NRFX=y

My main.c

#include <device.h>
#include <devicetree.h>
#include <drivers/gpio.h>
#include <drivers/spi.h>
#include <sys/printk.h>
#include <zephyr.h>

uint8_t arr[] = {
    0x02, 0x00, 0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x20, 
    0x57, 0x4f, 0x52, 0x4c, 0x44, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00
};

static struct spi_config spi_conf = {
	.frequency = 1000000U,
	.operation = (SPI_OP_MODE_MASTER | SPI_WORD_SET(8) | SPI_TRANSFER_MSB)
};

void sendDummyData(const struct device *dev) {
    uint8_t status;
    const struct spi_buf tx_buf[] = {{
        .buf = &arr,
        .len = 34
    }};
    const struct spi_buf_set tx = {
        .buffers = tx_buf,
        .count = 1};
    const struct spi_buf rx_buf = {
        .buf = &status,
        .len = 1};
    const struct spi_buf_set rx = {
        .buffers = &rx_buf,
        .count = 1};
    if (spi_transceive(dev, &spi_conf, &tx, &rx) != 0) {
        printk("Failed to exec rf2xx_reg_write at address");
    }
}

void main(void) {
    // struct device *port0 = device_get_binding("GPIO_0");
    struct device *port1 = device_get_binding("GPIO_1");
    gpio_pin_configure(port1, 12, GPIO_OUTPUT_LOW);  // Built-in led 1

    struct device *spi = device_get_binding("SPI_0");

    printk("Hello World! %s\n", CONFIG_BOARD);

    while (true) {
        gpio_pin_toggle(port1, 12);
        sendDummyData(spi);
        printk("Alive\n");
        k_msleep(1000);
    }
}

I don't know why, but as soon as spi_transceive happens, everything freezes.

What did I do wrong, how to solve it? 

Thanks.

Parents Reply Children
No Data
Related