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

While loop not terminating, but the event handler is called.

Hi,

I'm trying to run a display using SPI, and I've run into some troubles. I've attached my code below: 

#define SPI_INSTANCE  0 /**< SPI instance index. */
static const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
static volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */


static uint8_t       m_tx_buf[] = {CHARGEPUMP, 0x14, DISPLAYON , SETCONTRAST, 0xFF, 0xA5};      
static uint8_t       m_rx_buf[1];  
static const uint8_t m_length = sizeof(m_tx_buf);      


void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
                       void *                    p_context)
{
    spi_xfer_done = true;
    NRF_LOG_INFO("Transfer completed");
    NRF_LOG_FLUSH();
    /*if (m_rx_buf[0] != 0)
    {
        NRF_LOG_INFO(" Received:");
        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
    }*/
}

int main(void)
{
    bsp_board_init(BSP_INIT_LEDS);

    APP_ERROR_CHECK(NRF_LOG_INIT(NULL));
    NRF_LOG_DEFAULT_BACKENDS_INIT();

    nrf_drv_spi_config_t spi_config = NRF_DRV_SPI_DEFAULT_CONFIG;
    spi_config.ss_pin   = SPI_SS_PIN;
    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_SPI_FREQ_1M;
    APP_ERROR_CHECK(nrf_drv_spi_init(&spi, &spi_config, spi_event_handler, NULL));

    NRF_LOG_INFO("SPI example started");
    NRF_LOG_FLUSH();
    
    memset(m_rx_buf, 0, m_length);

    APP_ERROR_CHECK(nrf_drv_spi_transfer(&spi, m_tx_buf, sizeof(m_tx_buf), m_rx_buf, 0));
 
    while (!spi_xfer_done)
    {
      //NRF_LOG_INFO("loop");
      //NRF_LOG_FLUSH();
    }
    NRF_LOG_INFO("done");
    NRF_LOG_FLUSH();
}

My issue is that the program never gets past the while loop ("done" is never logged). The event handler however, is called ("Transfer complete" is logged). The really weird part is that if I uncomment the code in the while loop, "loop" is logged once, followed by nothing - not even "Transfer complete".

Commented ouptput: 

    <info> app: SPI example started
    <info> app: Transfer completed

Uncommented ouptput: 

    <info> app: SPI example started
    <info> app: loop

I appreciate any help anyone can offer. Thanks :)

Related