天天看點

STM32 UART1 DMA 發送資料

#define Uart_c

#include "include.h"

INT8U gUartBuf[16];

//DMA的配置

static void _Uart_DMA(void)

{

DMA_InitTypeDef DMA_InitStructure;

RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);

DMA_DeInit(DMA1_Channel4);

//指定DMA外設基位址

DMA_InitStructure.DMA_PeripheralBaseAddr =(u32)( &(USART1->DR));   //USART1的DR

//設定DMA記憶體基位址

DMA_InitStructure.DMA_MemoryBaseAddr = (u32)gUartBuf;      //擷取gUartBuf的數組

//外設作為資料傳輸的來源

DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;      //片内外設作目的地

//指定DMA通道的DMA緩存大小

DMA_InitStructure.DMA_BufferSize = 16;              //每次最多16個資料

//外設位址不遞增(不變)

DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; //外設位址不增加

//記憶體位址不遞增(不變)

DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;     //記憶體位址增加

//設定外設資料寬度為16位

DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; //Byte

DMA_InitStructure.DMA_MemoryDataSize = DMA_PeripheralDataSize_Byte;    //Byte

//設定DMA的工作模式普通模式,還有一種是循環模式

DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;         //普通模式

//設定DMA通道的軟體優先級

DMA_InitStructure.DMA_Priority = DMA_Priority_High;        //高優先級

//使能DMA記憶體到記憶體的傳輸,此處沒有記憶體到記憶體的傳輸

DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;         //非記憶體到記憶體

DMA_Init(DMA1_Channel4, &DMA_InitStructure);

DMA_ITConfig(DMA1_Channel4, DMA_IT_TC, DISABLE);         //DMA通道4傳輸完成中斷??

DMA_Cmd(DMA1_Channel4, DISABLE);

}

void fn_Uart_Init(INT32U BaudRate)

{

//ToDo: Add your code Here:

  USART_InitTypeDef USART_InitStructure;

  GPIO_InitTypeDef GPIO_InitStructure;  

 //uart PA IO

 {

   GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;

   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;

   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

   GPIO_Init(GPIOA,   &GPIO_InitStructure);

   // Configure USART0 Rx (PA.10) as input floating

   GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_10;

   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;         

   GPIO_Init(GPIOA, &GPIO_InitStructure);

 }

  RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 , ENABLE);//序列槽時鐘配置RCC_APB2Periph_USART1

  _Uart_DMA();//不能放錯位置

 USART_InitStructure.USART_BaudRate = BaudRate;

 USART_InitStructure.USART_WordLength = USART_WordLength_8b;

 USART_InitStructure.USART_StopBits = USART_StopBits_1;

 USART_InitStructure.USART_Parity = USART_Parity_No;

 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//無流控制

 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

 USART_Init(USART1, &USART_InitStructure);

 USART_DMACmd(USART1,USART_DMAReq_Tx,ENABLE);//使能UART1的DMA方式

 // 使能 USART1 

 USART_Cmd(USART1, ENABLE);

}

void fn_Uart_Send(INT8U *buf,INT8U num)

{

//ToDo: Add your code Here:

    INT8U i;

   DMA_Cmd(DMA1_Channel4, DISABLE);

 for(i=0;i<num;i++)

  gUartBuf[i]=buf[i];

  DMA_SetCurrDataCounter(DMA1_Channel4,num); 

  DMA_Cmd(DMA1_Channel4,ENABLE);

}