Beispiel #1
0
/*FUNCTION**********************************************************************
 *
 * Function Name : DSPI_DRV_MasterTransferBlocking
 * Description   : Perform a blocking SPI master mode transfer.
 * This function simultaneously sends and receives data on the SPI bus, as SPI is naturally
 * a full-duplex bus. The function will not return until the transfer is complete.
 *
 *END**************************************************************************/
dspi_status_t DSPI_DRV_MasterTransferBlocking(uint32_t instance,
                                              const dspi_device_t * device,
                                              const uint8_t * sendBuffer,
                                              uint8_t * receiveBuffer,
                                              size_t transferByteCount,
                                              uint32_t timeout)
{
    /* instantiate local variable of type dspi_master_state_t and point to global state */
    dspi_master_state_t * dspiState = (dspi_master_state_t *)g_dspiStatePtr[instance];
    SPI_Type *base = g_dspiBase[instance];
    dspi_status_t error = kStatus_DSPI_Success;

    /* If the transfer count is zero, then return immediately.*/
    if (transferByteCount == 0)
    {
        return error;
    }

    /* As this is a synchronous transfer, set up the sync status variable*/
    osa_status_t syncStatus;

    /* fill in members of the run-time state struct*/
    dspiState->isTransferBlocking = true; /* Indicates this is a blocking transfer */
    dspiState->sendBuffer = (const uint8_t *)sendBuffer;
    dspiState->receiveBuffer = (uint8_t *)receiveBuffer;
    dspiState->remainingSendByteCount = transferByteCount;
    dspiState->remainingReceiveByteCount = transferByteCount;

    /* start the transfer process*/
    if (DSPI_DRV_MasterStartTransfer(instance, device) == kStatus_DSPI_Busy)
    {
        return kStatus_DSPI_Busy;
    }

    /* As this is a synchronous transfer, wait until the transfer is complete.*/
    do
    {
        syncStatus = OSA_SemaWait(&dspiState->irqSync, timeout);
    }while(syncStatus == kStatus_OSA_Idle);

    /* If a timeout occurs, stop the transfer by setting the isTransferInProgress to false and
     * disabling interrupts, then return the timeout error status.
     */
    if (syncStatus != kStatus_OSA_Success)
    {
        /* The transfer is complete.*/
        dspiState->isTransferInProgress = false;

        /* Disable interrupt requests*/
        /* RX FIFO Drain request: RFDF_RE */
        DSPI_HAL_SetRxFifoDrainDmaIntMode(base, kDspiGenerateIntReq, false);

        /* Disable TX FIFO Fill request */
        DSPI_HAL_SetTxFifoFillDmaIntMode(base, kDspiGenerateIntReq, false);

        error = kStatus_DSPI_Timeout;
    }

    return error;
}
/*FUNCTION**********************************************************************
 *
 * Function Name : DSPI_DRV_DmaMasterTransferBlocking
 * Description   : Performs a blocking SPI master mode transfer with DMA support.
 *
 * This function simultaneously sends and receives data on the SPI bus, as SPI is naturally
 * a full-duplex bus. The function does not return until the transfer is complete.
 *
 *END**************************************************************************/
dspi_status_t DSPI_DRV_DmaMasterTransferBlocking(uint32_t instance,
        const dspi_dma_device_t * device,
        const uint8_t * sendBuffer,
        uint8_t * receiveBuffer,
        size_t transferByteCount,
        uint32_t timeout)
{
    /* instantiate local variable of type dspi_dma_master_state_t and point to global state */
    dspi_dma_master_state_t * dspiDmaState = (dspi_dma_master_state_t *)g_dspiStatePtr[instance];
    SPI_Type *base = g_dspiBase[instance];
    dspi_status_t error = kStatus_DSPI_Success;

    /* If the transfer count is zero, then return immediately.*/
    if (transferByteCount == 0)
    {
        return kStatus_DSPI_InvalidParameter;
    }

    dspiDmaState->isTransferBlocking = true; /* Indicates this is a blocking transfer */
    /* As this is a synchronous transfer, set up the sync status variable*/
    osa_status_t syncStatus;

    if (DSPI_DRV_DmaMasterStartTransfer(instance, device, sendBuffer, receiveBuffer,
                                        transferByteCount) == kStatus_DSPI_Busy)
    {
        return kStatus_DSPI_Busy;
    }

    /* As this is a synchronous transfer, wait until the transfer is complete.*/
    do
    {
        syncStatus = OSA_SemaWait(&dspiDmaState->irqSync, timeout);
    } while(syncStatus == kStatus_OSA_Idle);

    /* If a timeout occurs, stop the transfer by setting the isTransferInProgress to false and
     * disabling DMA requests and interrupts, then return the timeout error status.
     */
    if (syncStatus != kStatus_OSA_Success)
    {
        /* The transfer is complete.*/
        dspiDmaState->isTransferInProgress = false;

        /* Disable the Receive FIFO Drain DMA Request */
        DSPI_HAL_SetRxFifoDrainDmaIntMode(base, kDspiGenerateDmaReq, false);

        /* Disable TFFF DMA request */
        DSPI_HAL_SetTxFifoFillDmaIntMode(base, kDspiGenerateDmaReq, false);

        /* Disable End of Queue request */
        DSPI_HAL_SetIntMode(base, kDspiEndOfQueue, false);

        error = kStatus_DSPI_Timeout;
    }

    return error;
}
/*FUNCTION**********************************************************************
 *
 * Function Name : DSPI_DRV_DmaTxLastCallback
 * Description   : Callback function, this called when DMA transmitting the last frame
 * completed
 *
 *END**************************************************************************/
static void DSPI_DRV_DmaTxLastCallback(void *param, dma_channel_status_t status)
{
    uint32_t instance = (uint32_t)param;
    SPI_Type *base = g_dspiBase[instance];
    dspi_dma_master_state_t * dspiDmaState = (dspi_dma_master_state_t *)g_dspiStatePtr[instance];

    /* Stop DMA Tx channel */
    DMA_DRV_StopChannel(&dspiDmaState->dmaTxDataChannel);

    /* Disable Tx Fifo fill interrupt */
    DSPI_HAL_SetTxFifoFillDmaIntMode(base, kDspiGenerateDmaReq, false);
}
Beispiel #4
0
void dspi_slave_setup(uint32_t instance, uint32_t baudrate)
{
    dspi_data_format_config_t config;
    uint32_t baseAddr = SPI0_BASE;
    
    // Enable clock
    CLOCK_SYS_EnableSpiClock(instance);
    
    // Clear flags
    DSPI_HAL_ClearStatusFlag(g_dspiBaseAddr[instance], kDspiTxComplete);
    DSPI_HAL_ClearStatusFlag(g_dspiBaseAddr[instance], kDspiTxAndRxStatus);
    DSPI_HAL_ClearStatusFlag(g_dspiBaseAddr[instance], kDspiEndOfQueue);
    DSPI_HAL_ClearStatusFlag(g_dspiBaseAddr[instance], kDspiTxFifoUnderflow);
    DSPI_HAL_ClearStatusFlag(g_dspiBaseAddr[instance], kDspiTxFifoFillRequest);
    DSPI_HAL_ClearStatusFlag(g_dspiBaseAddr[instance], kDspiRxFifoOverflow);
    DSPI_HAL_ClearStatusFlag(g_dspiBaseAddr[instance], kDspiRxFifoDrainRequest);
    
    // Enable HAL
    DSPI_HAL_Init(baseAddr);
    DSPI_HAL_SetMasterSlaveMode(baseAddr, kDspiSlave);
    DSPI_HAL_Enable(baseAddr);

    // Disable transfer
    DSPI_HAL_StopTransfer(baseAddr);
    
    // PCS popularity
    DSPI_HAL_SetPcsPolarityMode(baseAddr, kDspiPcs0, kDspiPcs_ActiveLow);

    // CTAR
    DSPI_HAL_SetBaudRate(baseAddr, kDspiCtar0, baudrate, 72000000);
    config.bitsPerFrame = 16;
    config.clkPhase = kDspiClockPhase_FirstEdge;
    config.clkPolarity = kDspiClockPolarity_ActiveHigh;
    config.direction = kDspiMsbFirst;
    DSPI_HAL_SetDataFormat(baseAddr, kDspiCtar0, &config);

    // Interrupt
    INT_SYS_EnableIRQ(g_dspiIrqId[instance]);
    DSPI_HAL_SetIntMode(g_dspiBaseAddr[instance], kDspiTxFifoUnderflow, false);
    DSPI_HAL_SetIntMode(g_dspiBaseAddr[instance], kDspiTxFifoFillRequest, false);
    // DMA
    DSPI_HAL_SetTxFifoFillDmaIntMode(g_dspiBaseAddr[instance], kDspiGenerateIntReq, true);
    DSPI_HAL_SetRxFifoDrainDmaIntMode(g_dspiBaseAddr[instance], kDspiGenerateDmaReq, true);
}
/*!
 * @brief Finish up a transfer.
 * Cleans up after a transfer is complete. Interrupts are disabled, and the DSPI module
 * is disabled. This is not a public API as it is called from other driver functions.
 */
static void DSPI_DRV_DmaMasterCompleteTransfer(uint32_t instance)
{
    /* instantiate local variable of type dspi_dma_master_state_t and point to global state */
    dspi_dma_master_state_t * dspiDmaState = (dspi_dma_master_state_t *)g_dspiStatePtr[instance];
    SPI_Type *base = g_dspiBase[instance];

    /* The transfer is complete.*/
    dspiDmaState->isTransferInProgress = false;

    /* Disable the Receive FIFO Drain DMA Request */
    DSPI_HAL_SetRxFifoDrainDmaIntMode(base, kDspiGenerateDmaReq, false);

    /* Disable TFFF DMA request */
    DSPI_HAL_SetTxFifoFillDmaIntMode(base, kDspiGenerateDmaReq, false);

    if (dspiDmaState->isTransferBlocking)
    {
        /* Signal the synchronous completion object */
        OSA_SemaPost(&dspiDmaState->irqSync);
    }
}
/*!
 * @brief Initiate (start) a transfer using DMA. This is not a public API as it is called from
 *  other driver functions
 */
static dspi_status_t DSPI_DRV_DmaMasterStartTransfer(uint32_t instance,
        const dspi_dma_device_t * device,
        const uint8_t * sendBuffer,
        uint8_t * receiveBuffer,
        size_t transferByteCount)
{
    /* instantiate local variable of type dspi_dma_master_state_t and point to global state */
    dspi_dma_master_state_t * dspiDmaState = (dspi_dma_master_state_t *)g_dspiStatePtr[instance];
    /* For temporarily storing DMA instance and channel */
    uint8_t transferSizeInBytes = 1U;

    uint32_t calculatedBaudRate;
    dspi_command_config_t command;  /* create an instance of the data command struct*/
    SPI_Type *base = g_dspiBase[instance];
    uint32_t txTransferByteCnt = 0;
    uint32_t rxTransferByteCnt = 0;

    /* Initialize s_wordToSend */
    s_wordToSend = 0;

    /* Check that we're not busy.*/
    if (dspiDmaState->isTransferInProgress)
    {
        return kStatus_DSPI_Busy;
    }

    /* Calculate the transfer size on bits/frame */
    if (dspiDmaState->bitsPerFrame <= 8)
    {
        transferSizeInBytes = 1U;
    }
    else if (dspiDmaState->bitsPerFrame <= 16)
    {
        transferSizeInBytes = 2U;
    }
    else
    {
        transferSizeInBytes = 4U;
    }

    /* Configure bus for this device. If NULL is passed, we assume the caller has
     * preconfigured the bus using DSPI_DRV_DmaMasterConfigureBus().
     * Do nothing for calculatedBaudRate. If the user wants to know the calculatedBaudRate
     * then they can call this function separately.
     */
    if (device)
    {
        DSPI_DRV_DmaMasterConfigureBus(instance, device, &calculatedBaudRate);
        dspiDmaState->bitsPerFrame = device->dataBusConfig.bitsPerFrame; /*update bits/frame*/
    }

    /* Check the transfer byte count. If bits/frame > 8, meaning 2 bytes, and if
     * the transfer byte count is an odd count we'll have to increase the TX transfer byte count
     * by one and assert a flag to indicate to the send functions that it will
     * need to handle an extra byte.
     * For receive, we actually round down the transfer count to the next lowest even number.
     * Then in the interrupt handler, we take care of geting this last byte.
     */
    if ((dspiDmaState->bitsPerFrame > 8) && (transferByteCount & 1UL))
    {
        dspiDmaState->extraByte = true;
        txTransferByteCnt = transferByteCount + 1U;  /* Increment to next even byte count */
        rxTransferByteCnt = transferByteCount & ~1U;  /* Decrement to next even byte count */
    }
    else
    {
        dspiDmaState->extraByte = false;
        txTransferByteCnt = transferByteCount;
        rxTransferByteCnt = transferByteCount;
    }
    /* Store the receiveBuffer pointer and receive byte count to the run-time state struct
     * for later use in the interrupt handler.
     */
    dspiDmaState->rxBuffer = (uint8_t *)receiveBuffer;
    dspiDmaState->rxTransferByteCnt = rxTransferByteCnt;

    /* Save information about the transfer for use by the ISR.*/
    dspiDmaState->isTransferInProgress = true;

    /* Reset the transfer counter to 0. Normally this is done via the PUSHR[CTCNT], but as we
     * are under DMA controller, we won't be able to change this bit dynamically after the
     * first word is transferred.
     */
    DSPI_HAL_PresetTransferCount(base, 0);

    /* flush the fifos*/
    DSPI_HAL_SetFlushFifoCmd(base, true, true);

    /* Clear status flags that may have been set from previous transfers */
    DSPI_HAL_ClearStatusFlag(base, kDspiTxComplete);
    DSPI_HAL_ClearStatusFlag(base, kDspiEndOfQueue);
    DSPI_HAL_ClearStatusFlag(base, kDspiTxFifoUnderflow);
    DSPI_HAL_ClearStatusFlag(base, kDspiTxFifoFillRequest);
    DSPI_HAL_ClearStatusFlag(base, kDspiRxFifoOverflow);
    DSPI_HAL_ClearStatusFlag(base, kDspiRxFifoDrainRequest);

    /************************************************************************************
     * Set up the RX DMA channel Transfer Control Descriptor (TCD)
     * Do this before filling the TX FIFO.
     * Note, if there is no remaining receive count, then bypass RX DMA set up.
     * This means we only have one byte to read of a 16-bit data word and will read this
     * in the complete transfer function.
     ***********************************************************************************/
    /* If a receive buffer is used and if rxTransferByteCnt > 0 */
    if (rxTransferByteCnt)
    {
        if (!receiveBuffer)
        {
            /* Set up this channel's control which includes enabling the DMA interrupt */
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaRxChannel,
                                   kDmaPeripheralToPeripheral,
                                   transferSizeInBytes,
                                   DSPI_HAL_GetPoprRegAddr(base), /* src is data register */
                                   (uint32_t)(&s_rxBuffIfNull), /* dest is temporary location */
                                   (uint32_t)(rxTransferByteCnt));
        }
        else
        {
            /* Set up this channel's control which includes enabling the DMA interrupt */
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaRxChannel,
                                   kDmaPeripheralToMemory,
                                   transferSizeInBytes,
                                   DSPI_HAL_GetPoprRegAddr(base), /* src is data register */
                                   (uint32_t)(receiveBuffer), /* dest is rx buffer */
                                   (uint32_t)(rxTransferByteCnt));

            /* Destination size is only 1 byte */
            DMA_DRV_SetDestTransferSize(&dspiDmaState->dmaRxChannel, 1U);
        }

        /* Enable the DMA peripheral request */
        DMA_DRV_StartChannel(&dspiDmaState->dmaRxChannel);
    }
    else if (dspiDmaState->extraByte)
    {
        /* Need to receive only one frame - extra byte by calling Rx callback function*/
        DSPI_DRV_DmaRxCallback((void *)instance, kDmaIdle);
    }

    /************************************************************************************
     * Set up the Last Command/data Word Intermediate Buffer and fill up the TX FIFO.
     ***********************************************************************************/
    /* Before sending the data, we first need to initialize the data command struct
     * Configure the data command attributes for the desired PCS, CTAR, and continuous PCS
     * which are derived from the run-time state struct
     */
    command.whichPcs = dspiDmaState->whichPcs;
    command.whichCtar = dspiDmaState->whichCtar;
    command.clearTransferCount = false; /* don't clear the transfer count */

    /************************************************************************
     * Next, set up the Last Command/data Word Intermediate Buffer before
     * filling up the TX FIFO
     * Create a 32-bit word with the final 16-bit command settings. This means
     * that EOQ = 1 and CONT = 0.
     * This 32-bit word will also be initialized with the final data byte/word
     * from the send source buffer and then the entire 32-bit word will be
     * transferred to the DSPI PUSHR.
     ************************************************************************/
    /* Declare a variable for storing the last send data (either 8- or 16-bit) */
    uint32_t lastWord = 0;

    /* If a send buffer was provided, the word comes from there. Otherwise we just send
     * a zero (initialized above).
     */
    if (sendBuffer)
    {
        /* Store the last byte from the send buffer */
        if (dspiDmaState->bitsPerFrame <= 8)
        {
            lastWord = sendBuffer[txTransferByteCnt-1]; /* Last byte */
        }
        /* Store the last two bytes the send buffer */
        else
        {
            /* If 16-bit transfers and odd transfer byte count then an extra byte was added
             * to the transfer byte count, but we cannot access more of the send buffer
             */
            if(!dspiDmaState->extraByte)
            {
                lastWord = sendBuffer[txTransferByteCnt-1] ; /* Save off the last byte */
                lastWord = lastWord << 8U; /* Shift to MSB (separate step due to MISHA) */
            }
            lastWord |= sendBuffer[txTransferByteCnt-2]; /* OR with next to last byte */
        }
    }

    /* Now, build the last command/data word intermediate buffer */
    command.isChipSelectContinuous = false; /* Always clear CONT for last data word */
    command.isEndOfQueue = true; /* Set EOQ for last data word */
    s_lastCmdData = DSPI_HAL_GetFormattedCommand(base, &command) | lastWord;
    /************************************************************************
     * Begin TX DMA channels transfer control descriptor set up.
     * 1. First, set up intermediate buffers which contain 16-bit commands.
     * 2. Set up the DMA Software Transfer Control Descriptors (STCD) for various
     *    scenarios:
     *    - Channel for intermediate buffer to TX FIFO
     *    - Channel for source buffer to intermediate buffer
     *    - STCD for scatter/gather for end of previous channel to replace
     *      intermediate buffer with last-command buffer.
     ************************************************************************/

    /************************************************************************
     * Intermediate Buffer
     * Create a 32-bit word with the 16-bit command settings. Data from
     * the send source buffer will be transferred here and then the entire
     * 32-bit word will be transferred to the DSPI PUSHR.
     * This buffer will be preloaded with the next data word in the send buffer
     ************************************************************************/
    /* restore the isChipSelectContinuous setting to the original value as it was cleared above */
    command.isChipSelectContinuous = dspiDmaState->isChipSelectContinuous;
    command.isEndOfQueue = false; /* Clear End of Queue (previously set for last cmd/data word)*/
    s_cmdData = DSPI_HAL_GetFormattedCommand(base, &command);

    /* Place the next data from the send buffer into the intermediate buffer (preload it)
     * based on whether it is one byte or two.
     */
    if (dspiDmaState->bitsPerFrame <= 8)
    {
        /* If a send buffer was provided, the word comes from there. Otherwise we just send
         * a zero (initialized above).
         */
        if (sendBuffer)
        {
            s_wordToSend = *sendBuffer;  /* queue up the next data */
            ++sendBuffer; /* increment to next data word*/
        }
        --txTransferByteCnt; /* decrement txTransferByteCnt*/
    }
    else
    {
        /* If a send buffer was provided, the word comes from there. Otherwise we just send
         * a zero (initialized above).
         */
        if (sendBuffer)
        {
            s_wordToSend = *sendBuffer;
            ++sendBuffer; /* increment to next data byte */

            /* Note, if the extraByte flag is set and we're down to the last two bytes we can still
             * do this even though we're going past the sendBuffer size. We're just reading data we
             * don't care about anyways since it is dummy data to make up for the last byte.
             */
            s_wordToSend |= (unsigned)(*sendBuffer) << 8U;
            ++sendBuffer; /* increment to next data byte */

        }
        txTransferByteCnt -= 2;  /* decrement txTransferByteCnt by 2 bytes */
    }

    s_cmdData |= s_wordToSend; /* write s_wordToSend to intermediate buffer */

    /* For Tx, DSPI need two DMA channel, one for calculate the command and data into one value
     * (dmaTxCmdChannel), and another for push the value into DSPI PUSHR register (dmaTxDataChannel).
     * The dmaTxCmdChannel DMA channel will be triggered by DSPI Tx FIFO, and the dmaTxDataChannel
     * DMA channel will be linked to calculate DMA channel and triggered by this channel also.
     */

    /* If the transfer size is less than size of one frame, only transmit the last byte that calculated */
    if (!txTransferByteCnt)
    {
        DMA_DRV_ConfigTransfer(&dspiDmaState->dmaTxDataChannel, kDmaMemoryToPeripheral,
                               4u, (uint32_t)(&s_lastCmdData),
                               DSPI_HAL_GetMasterPushrRegAddr(base), 4u);
        /* Register callback for last byte transmitting */
        DMA_DRV_RegisterCallback(&dspiDmaState->dmaTxDataChannel, DSPI_DRV_DmaTxLastCallback, (void *)instance);
    }
    else
    {
        /* Config DMA to copy data from generated cmd data to FIFO */
        if (dspiDmaState->bitsPerFrame <= 8)
        {
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaTxDataChannel, kDmaPeripheralToPeripheral,
                                   4u, (uint32_t)(&s_cmdData),
                                   DSPI_HAL_GetMasterPushrRegAddr(base),
                                   (uint32_t)((txTransferByteCnt) * 4));
        }
        else
        {
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaTxDataChannel, kDmaPeripheralToPeripheral,
                                   4u, (uint32_t)(&s_cmdData),
                                   DSPI_HAL_GetMasterPushrRegAddr(base),
                                   (uint32_t)((txTransferByteCnt) * 2));
        }
        /* Register Tx callback function */
        DMA_DRV_RegisterCallback(&dspiDmaState->dmaTxDataChannel, DSPI_DRV_DmaTxCallback, (void *)instance);

        /* Config dmaTxCmdChannel channel if send buffer is provided */
        if (sendBuffer)
        {
            dma_channel_link_config_t config;
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaTxCmdChannel, kDmaMemoryToPeripheral,
                                   1u, (uint32_t)(sendBuffer),
                                   (uint32_t)(&s_cmdData),
                                   (uint32_t)(txTransferByteCnt - transferSizeInBytes));
            if (dspiDmaState->bitsPerFrame > 8)
            {
                DMA_DRV_SetDestTransferSize(&dspiDmaState->dmaTxCmdChannel, 2U);
            }

            /* Link dmaTxCmdChannel after dmaTxDataChannel */
            config.channel1 = dspiDmaState->dmaTxCmdChannel.channel;
            config.channel2 = 0;
            config.linkType = kDmaChannelLinkChan1;
            DMA_DRV_ConfigChanLink(&dspiDmaState->dmaTxDataChannel, &config);
            /* start channel */
            DMA_DRV_StartChannel(&dspiDmaState->dmaTxCmdChannel);
        }
    }

    /* Register callback */
    DMA_DRV_RegisterCallback(&dspiDmaState->dmaRxChannel, DSPI_DRV_DmaRxCallback, (void *)instance);

    /* Enable the Receive FIFO Drain DMA Request */
    DSPI_HAL_SetRxFifoDrainDmaIntMode(base, kDspiGenerateDmaReq, true);

    /* Enable TFFF DMA request */
    DSPI_HAL_SetTxFifoFillDmaIntMode(base, kDspiGenerateDmaReq, true);

    /* Enable the DMA peripheral request */
    DMA_DRV_StartChannel(&dspiDmaState->dmaTxDataChannel);

    return kStatus_DSPI_Success;
}