

#include <nrfx_example.h>
#include <nrfx_spis.h>

#define NRFX_LOG_MODULE                 EXAMPLE
#define NRFX_EXAMPLE_CONFIG_LOG_ENABLED 1
#define NRFX_EXAMPLE_CONFIG_LOG_LEVEL   3
#include <nrfx_log.h>

/** @brief Symbol specifying SPIM instance to be used. */
#define SPIS_INST_IDX 2

#define APP_SPIS_CS_PIN (4)
#define APP_SPIS_SCK_PIN (5)
#define APP_SPIS_MISO_PIN (6)
#define APP_SPIS_MOSI_PIN (7)

static nrfx_spis_config_t spis_config =
	NRFX_SPIS_DEFAULT_CONFIG(APP_SPIS_SCK_PIN, APP_SPIS_MOSI_PIN, APP_SPIS_MISO_PIN, APP_SPIS_CS_PIN);
#define TEST_STRING "0987654321"

static uint8_t m_tx_buf[] = TEST_STRING; /**< TX buffer. */
static uint8_t m_rx_buf[sizeof(TEST_STRING) + 1]; /**< RX buffer. */


static const uint8_t m_length = sizeof(m_tx_buf); /**< Transfer length. */

static volatile bool
	spis_xfer_done; /**< Flag used to indicate that SPIS instance completed the transfer. */



static void spis_event_handler(nrfx_spis_evt_t const * event, void * p_context)
{

    NRFX_LOG_INFO("ISR: %d\n", event->evt_type);
	if (event->evt_type == NRFX_SPIS_XFER_DONE) {		
		NRFX_LOG_INFO("bytes rx: %d\n", event->rx_amount);
		NRFX_LOG_INFO("%s", m_rx_buf);
		spis_xfer_done = true;
	}	
}

/**
 * @brief Function for application main entry.
 *
 * @return Nothing.
 */
int main(void)
{
    nrfx_err_t status;
    (void)status;

    NRFX_EXAMPLE_LOG_INIT();

    NRFX_LOG_INFO("SPIS example\n");
    NRFX_EXAMPLE_LOG_PROCESS();

   nrfx_spis_t spis_inst = NRFX_SPIS_INSTANCE(SPIS_INST_IDX);

   void * p_context = "Some context";

    if (NRFX_SUCCESS !=
	    nrfx_spis_init(&spis_inst, &spis_config, spis_event_handler, p_context)) {
		NRFX_LOG_INFO("Init Failed");
		return 0;
	}


#if defined(__ZEPHYR__)
    #define SPIS_INST         NRFX_CONCAT_2(NRF_SPIS, SPIS_INST_IDX)
    #define SPIS_INST_HANDLER NRFX_CONCAT_3(nrfx_spis_, SPIS_INST_IDX, _irq_handler)
    IRQ_DIRECT_CONNECT(NRFX_IRQ_NUMBER_GET(SPIS_INST), IRQ_PRIO_LOWEST, SPIS_INST_HANDLER, 0)
#endif

while(1) {
memset(m_rx_buf, 0x55, m_length);
		spis_xfer_done = false;

		if (NRFX_SUCCESS != nrfx_spis_buffers_set(&spis_inst, m_tx_buf,
							  m_length, m_rx_buf,
							  m_length)) {
			NRFX_LOG_INFO("Receive Failed");
			//return 0;
		}

		while (!spis_xfer_done) {
			//__WFE();
            NRFX_EXAMPLE_LOG_PROCESS();
		}
	}
}

/** @} */
