#include "msp430.h"
#define CPU ((double)4000000)
#define delay_ms(x) __delay_cycles((long)(CPU*(double)x/1000.0))
#define delay_us(x) __delay_cycles((long)(CPU*(double)x/1000000.0))
#define TX_Num 10 //发送数组大小
#define RX_Num 10 //接收数组大小
#define Frame_Header 0xEE //接收帧头
#define Frame_End 0xFF //接收帧尾
void XT_init(void); //晶振初始化函数
void Receive_Handle(void); //接收处理函数
void DMA_init(void); //DMA初始化理函数
unsigned char TxString[TX_Num]; //发送数组
unsigned char RxString[RX_Num]; //接收数组
unsigned char RX_Succeed; //接收正确标志
int main( void )
{
// Stop watchdog timer to prevent time out reset
WDTCTL = WDTPW + WDTHOLD;
XT_init(); //晶振初始化
//初始化串口
P4SEL |= BIT4+BIT5; //选择P4.4、P4.5 为串口1
UCA1CTL1 |= UCSWRST; // **Put state machine in reset**
UCA1CTL1 |= UCSSEL__ACLK; //串口时钟源为ACLK ,在初始化为32.768kHz
UCA1BR0 = 3; // 32768 9600 (see User's Guide)
UCA1BR1 = 0; // 32768 9600
UCA1MCTL |= UCBRS_3 + UCBRF_0; // Modulation UCBRSx=3, UCBRFx=0
UCA1CTL1 &= ~UCSWRST; // **Initialize USCI state machine**
DMA_init(); //DMA初始化
_EINT();
while(1)
{
if (RX_Succeed==1) //正确接收
{
RX_Succeed=0; //清除接收标志
DMA1CTL|=DMAEN; //启动DMA通道1发送数据
}
}
}
void DMA_init(void)
{
int i=0;
DMACTL0 = DMA0TSEL_20|DMA1TSEL_21; // 通道0接收数据,通道1发送数据
DMA0CTL&=~DMAIFG; //先清除通道0中断标志位
DMA1CTL&=~DMAIFG; //先清除通道1中断标志位
//配置通道0接收
DMACTL4=DMARMWDIS; //禁止任何发生在CPU 读写操作时候的DMA传输
//重复单次传输+开启使能+目标地址增加+字节传输 +开启中断
DMA0CTL = DMADT_4 + DMAEN + DMADSTINCR_3+DMADSTBYTE+ DMAIE;
DMA0SZ = RX_Num; // 接收字节大小
__data16_write_addr((unsigned short) &DMA0SA,(unsigned long) &UCA1RXBUF);//源地址为串口1接收地址
__data16_write_addr((unsigned short) &DMA0DA,(unsigned long) &RxString);//目的地址是接收数组
//配置通道1发送
//单次传输+源地址增加+字节传输 +电平触发+ 开启中断
DMA1CTL = DMADT_0 + DMASRCINCR_3 + DMASRCBYTE + DMALEVEL + DMAIE;
DMA1SZ = TX_Num; // 发送字节大小
__data16_write_addr((unsigned short) &DMA1SA,(unsigned long) &TxString);//源地址为发收数组
__data16_write_addr((unsigned short) &DMA1DA,(unsigned long) &UCA1TXBUF);//目的地址是串口1发送地址
//初始化发送数组
for(i=0;i<10;i++)
{
TxString=0x0a+i;
}
}
#pragma vector=DMA_VECTOR
__interrupt void DMA_ISR(void)
{
switch(__even_in_range(DMAIV,4))
{
case 0x00:
break;
case 0x02: //通道0 接收到数组
Receive_Handle();
break;
}
}
void Receive_Handle(void)
{
if(RxString[0]==Frame_Header&&RxString[RX_Num-1]==Frame_End)//数据接收正确
{
//对数据进行处理
RX_Succeed=1; //接收正确标志
}
}
void XT_init(void)
{
P5SEL |= BIT4|BIT5|BIT2|BIT3; // Select XT1、XT2
UCSCTL6 &= ~(XT1OFF|XT2OFF); // XT1、XT2 On
UCSCTL6 |= XCAP_3; // Internal load cap
do
{
UCSCTL7 &= ~(XT2OFFG + XT1LFOFFG + DCOFFG);
SFRIFG1 &= ~OFIFG; // Clear fault flags
}while (SFRIFG1&OFIFG); // Test oscillator fault flag
UCSCTL6 &= ~(XT1DRIVE_3+XT2DRIVE0); // Xtal is now stable, reduce drive strength
UCSCTL4 =SELA_0+SELS__XT2CLK+SELM__XT2CLK;
UCSCTL5|=DIVS__4; //ACLK 32768,SMCLK 1M ,MCLK 4
}
|