I am trying to write SPI code for the nRF52840 dongle. Since the nRF5 SDK does not directly provide an example for the dongle, I followed the steps defined in this tutorial: https://devzone.nordicsemi.com/guides/short-range-guides/b/getting-started/posts/nrf52840-dongle-programming-tutorial. However, it is not working.
As I am just testing a simple code, I don't think the issue lies in the code itself—there might be some other problem.
Also, sometimes the code works once (not in a loop), but the same code fails to work later.
my code
#include "nrf_drv_spi.h"
#include "nrf_delay.h"
#include "app_error.h"
#include "nrf_gpio.h"
#include <stdbool.h>
#include <stdint.h>
#include "boards.h"
#define SPI_INSTANCE 0 // SPI instance index
#define SPI_CS_PIN 20 // Example: P0.12 (available on dongle)
#define SPI_SCK_PIN 15 // Example: P0.15 (available on dongle)
#define SPI_MOSI_PIN 14 // Example: P0.13 (if available, else use another)
#define SPI_MISO_PIN 13 // Example: P0.14 (available on dongle)
static const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);
static volatile bool spi_xfer_done;
uint8_t tx_buf[] = {0xAA, 0xBB, 0xCC, 0x0F};
uint8_t rx_buf[sizeof(tx_buf)];
void spi_event_handler(nrf_drv_spi_evt_t const * p_event, void * p_context)
{
spi_xfer_done = true;
}
void spi_init(void)
{
nrf_drv_spi_config_t spi_config = NRF_DRV_SPI_DEFAULT_CONFIG;
spi_config.ss_pin = SPI_CS_PIN; // Manual CS
spi_config.miso_pin = SPI_MISO_PIN;
spi_config.mosi_pin = SPI_MOSI_PIN;
spi_config.sck_pin = SPI_SCK_PIN;
spi_config.frequency = NRF_DRV_SPI_FREQ_500K;
spi_config.mode = NRF_DRV_SPI_MODE_0;
spi_config.bit_order = NRF_DRV_SPI_BIT_ORDER_MSB_FIRST;
APP_ERROR_CHECK(nrf_drv_spi_init(&spi, &spi_config, spi_event_handler, NULL));
}
int main(void)
{
spi_init();
while (1) {
spi_xfer_done = false;
APP_ERROR_CHECK(nrf_drv_spi_transfer(&spi, tx_buf, sizeof(tx_buf), rx_buf, sizeof(rx_buf)));
while (!spi_xfer_done) {
__WFE();
}
nrf_delay_ms(1);
}
}