/*
  ******************************************************************************
  * Copyright (c)  2008 - 2024, Shanghai AisinoChip Co.,Ltd .
  * @file    APP.c 
  * @version V1.0.0
  * @date    2022
  * @author  Aisinochip Firmware Team  
  * @brief   DMA demo source code.
  ******************************************************************************        
*/
 
#include  "app.h"
#include  "mpu_config.h"



extern uint8_t gu8_Tx1_DMA_Buffer[64]; 

volatile uint32_t dma_complete_times;

volatile uint32_t gu32_DMA_Status = false;   


void UART_TX_DMA_Init(void)
{   
    DMA_InitTypeDef DMA_InitStruct = {0};
    
    UART_DMACmd(UART2, UART_CR1_TXDMAE, DISABLE);
    
    __RCC_DMA1_CLK_ENABLE();    
    NVIC_ClearPendingIRQ(DMA1_IRQn);
    NVIC_EnableIRQ(DMA1_IRQn);   
    
    DMA_DeInit(DMA1_Channel0);
    
    DMA_InitStruct.Mode        = DMA_MODE_NORMAL;
    DMA_InitStruct.DataFlow    = DMA_DATAFLOW_M2P;
    DMA_InitStruct.ReqID       = DMA1_REQ7_UART2_SEND;
    DMA_InitStruct.RawInt      = DMA_RAWINT_ENABLE;
    DMA_InitStruct.SrcWidth    = DMA_SRCWIDTH_BYTE;
    DMA_InitStruct.DestWidth   = DMA_DESTWIDTH_BYTE;
    DMA_InitStruct.SrcInc      = DMA_SRCINC_ENABLE;
    DMA_InitStruct.DestInc     = DMA_DESTINC_DISABLE;
    DMA_InitStruct.SrcBurst    = DMA_SRCBURST_1;
    DMA_InitStruct.DestBurst   = DMA_DESTBURST_1;
    
    DMA_InitStruct.SrcAddr     = (uint32_t)gu8_Tx1_DMA_Buffer;
    DMA_InitStruct.DestAddr    = (uint32_t)(&UART2->DR);
    DMA_InitStruct.Size        = DMA_TX_SIZE;
    
    DMA_Init(DMA1_Channel0, &DMA_InitStruct);    
    
//    NVIC_ClearPendingIRQ(DMA1_IRQn);
//    NVIC_EnableIRQ(DMA1_IRQn);    
}

// Send UART Data by DMA 
void APP_Test(void)
{
    uint32_t len=64; 

    MPU_PrintReg();
    DelayMs(1000);
      
    //prepare data
    memset(gu8_Tx1_DMA_Buffer,0x31,len);
    memcpy(gu8_Tx1_DMA_Buffer, "Buffer1111111111", 16);   // Buffer1 flag
    gu8_Tx1_DMA_Buffer[len-4] = ',';    
    gu8_Tx1_DMA_Buffer[len-2] = '\r';
    gu8_Tx1_DMA_Buffer[len-1] = '\n';

    dma_complete_times = 0;

    while(1)
    {
        UART_TX_DMA_Init();
        //modify data count
        gu8_Tx1_DMA_Buffer[len-3] = (0x30 + dma_complete_times%10);
        
        //start dma transmit
        /* Enable DMA Channel0 transfer */
        DMA_Cmd(DMA1_Channel0, ENABLE);
        //UART DMA Send
        UART_DMACmd(UART2, UART_CR1_TXDMAE, ENABLE);			
        while (RESET == DMA_GetFlagStatus(DMA1_Channel0, DMA_FLAG_RTC));
        DMA_ClearFlag(DMA1_Channel0, DMA_FLAG_RTC);
        dma_complete_times++;            
    }
    

}

