#include "msp430f149.h"
#define Number_of_Results 5
unsigned int results[Number_of_Results];
unsigned int average = 0;
unsigned int nADC_Flag = 0 ;
unsigned int index = 0;
void Init_CLK(void)
{
unsigned int iq0;
BCSCTL1&=~0X00; //打开XT2振荡器
do
{
IFG1 &= ~OFIFG; // 清除振荡器失效标志
for (iq0 = 0xFF; iq0 > 0; iq0--); // 延时,等待XT2起振
}
while ((IFG1 & OFIFG) != 0); // 判断XT2是否起振
BCSCTL2 =SELM_2+SELS; //选择MCLK、SMCLK为XT2
}
void Init_ADC(void)
{
//设置P6.0为模拟输入通道
P6SEL = 0x01;
//设置ENC为0,从而修改ADC12寄存器的值
ADC12CTL0 &= ~(ENC);
//打开ADC12内核
ADC12CTL0 |= ADC12ON + SHT0_2;
//转换的起始地址为:ADCMEM0
ADC12CTL1 |= CSTARTADD_0;
//选择通道为A0
ADC12MCTL0 = INCH_0;
//5 单通道单次转换
ADC12CTL1 |= CONSEQ_0+SHS_1;
//时钟源为SMCLK
ADC12CTL1 |= ADC12SSEL_3;
//ADC时钟源分频
// ADC12CTL1 |= ADC12DIV_7;
ADC12CTL1 |= SHP;
//使能ADC
ADC12CTL0 |= ENC;
}
void Init_TimerA(void)
{
TACTL = TASSEL1 + TACLR+MC0;//TimerA选用SMCLK,计数器清零,增计数模式
//八分频
TACTL += ID1;
TACTL += ID0;
//频率为1000HZ;
CCR0 = 2000;
//CCR0允许中断
CCTL0 = CCIE;
}
void Init_UART(void)
{
P3SEL |= 0x30; // P3.4,5 = USART0 TXD/RXD
ME1 |= URXE0 + UTXE0; // Enable USART0 T/RXD
UCTL0 |= CHAR; // 8-bit character
UTCTL0 |= SSEL1; // UCLK = SMCLK
UBR00 = 0x1A; // 38400 32k/9600 - 3.41
UBR10 = 0x00; //
UMCTL0 = 0x00; // Modulation
UCTL0 &= ~SWRST; // Initialize USART state machine
}
void Send1Char(unsigned char sendchar)
{
while (!(IFG1 & UTXIFG0)); //等待发送寄存器为空
TXBUF0 = sendchar;
}
void PutString0(unsigned char *ptr)
{
while(*ptr != ' ')
{
Send1Char(*ptr++); // 发送数据
}
}
void PutString(unsigned char*ptr)
{
while(*ptr != ' ')
{
Send1Char(*ptr++); // 发送数据
}
while (!(IFG1 & UTXIFG0));
TXBUF0 = ';';
//发送换行指令
}
void Trans_val( unsigned int Hex_Val, unsigned char *ptr)
{
unsigned long caltmp;
unsigned Curr_Volt;
unsigned t1;
caltmp = Hex_Val;
caltmp = (caltmp << 5) + Hex_Val; //caltmp = Hex_Val * 33
caltmp = (caltmp << 3) + (caltmp << 1); //caltmp = caltmp * 10
Curr_Volt = caltmp >> 12; //Curr_Volt = caltmp / 2^n
ptr[0] = Curr_Volt / 100; //Hex->Dec变换
t1 = Curr_Volt - (ptr[0] * 100);
ptr[1] = t1 / 10;
ptr[2] = t1 - (ptr[1] * 10);
return;
}
void main()
{
unsigned char i=0;
unsigned char buffer[6];
buffer[5] = ' ';
WDTCTL = WDTPW + WDTHOLD;
/*下面六行程序关闭所有的IO口*/
P1DIR = 0XFF;P1OUT = 0XFF;
P2DIR = 0XFF;P2OUT = 0XFF;
P3DIR = 0XFF;P3OUT = 0XFF;
P4DIR = 0XFF;P4OUT = 0XFF;
P5DIR = 0XFF;P5OUT = 0XFF;
P6DIR = 0XFF;P6OUT = 0XFF;
_DINT();
Init_CLK();
Init_ADC();
Init_TimerA();
Init_UART();
_EINT();
for(;;)
{
if(nADC_Flag==1)
{
nADC_Flag = 0 ;
Trans_val(average,buffer);
buffer[4]=0x3b-0x30;
buffer[3]= buffer[2];
buffer[2] = buffer[1];
buffer[1] = '.'-0x30;
for(i = 0; i < 4; i++)
buffer[i] += 0x30;
PutString(buffer);
}
}
}
#pragma vector=TIMERA0_VECTOR
__interrupt void Timer_A(void)
{
//static int index = 0;
// ADC12CTL0 &= ~ENC;
results[index++] = ADC12MEM0;
if(index == Number_of_Results)
{
index = 0;
nADC_Flag = 1;
unsigned char i = 0;
for(i = 0 ; i < Number_of_Results ; i++)
{
average +=results[i];
}
average >>= 5 ;
}
ADC12CTL0 |= ADC12SC ;
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>