程序利用上升沿捕获功能,在1ms内记录捕捉到的脉冲个数,并通过串口助手显示:
/******************************************************************************
频率采集:时基为1ms,采用Timer0捕捉比较,记录时基内捕捉到的上升沿个数
P1.2-->Timer0_CCI1A 捕获输入
******************************************************************************/
#include"msp430x21x2.h"
volatile unsigned long int fCounter;
volatile char tCounter,mark=0;
unsigned char pcString []="当前频率:";
#define delay10us _NOP(),_NOP(),_NOP(),_NOP(),_NOP()
void Usart_PutChar(unsigned char cTXData) //字节发送函数
{
while (!(IFG2&UCA0TXIFG));
UCA0TXBUF = cTXData; // TX -> RXed character
}
void Usart_PutString(unsigned char *pcString)
{
while (*pcString)
{
Usart_PutChar(*pcString++);
}
//Usart_PutChar(0x0D);
//Usart_PutChar(0x0A); //结尾发送回车换行
}
void main()
{
WDTCTL =WDTPW +WDTHOLD;//Stop Watch dog
if (CALBC1_1MHZ ==0xFF || CALDCO_1MHZ == 0xFF)
{
while(1); // If calibration constants erased do not load, trap CPU!!
}
BCSCTL1 =CALBC1_1MHZ; //设定DCO为1MHZ
DCOCTL = CALDCO_1MHZ; //设定DCO 为1MHZ
unsigned int counter;
P1DIR |=BIT0;
P1SEL |=BIT2;
P1DIR &=~BIT2;//Timer0_A3, capture: CCI1A input
P1SEL2 &=~BIT2;
P3SEL= BIT5+BIT4;
TAR =0XFC18; //初装值65536-64536=1000us
TACCTL1 =CAP;
TACCTL1|=CM_1+CCIS_0+SCS+CCIE; //上升沿捕获,CCI0A输入,同步捕获,捕获中断使能
TACTL =TASSEL_2+TAIE+MC_0;//定时器时钟源SMCLK,连续模式,
UCA0CTL1 |= UCSWRST;
UCA0CTL1 |=UCSSEL_2; //SMCLK
UCA0BR0 = 104; //9600波特率
UCA0BR1 = 0;
UCA0MCTL =UCBRS_1;
UCA0CTL1 &=~UCSWRST;
IE2 |=UCA0RXIE; //接收中断使能*/
__bis_SR_register(GIE);
TACTL |=MC_2; //开启定时器
while(1)
{
while(mark==0);
mark=0;
counter=fCounter/1000;
fCounter=0;
//if(counter>1)
// {
Usart_PutString(pcString);
Usart_PutChar(counter/1000+0x30);
Usart_PutChar(counter%1000/100+0x30);
Usart_PutChar(counter%1000%100/10+0x30);
Usart_PutChar(counter%1000%100%10+0x30);
Usart_PutString("KHZ");
Usart_PutChar(0x0D);
Usart_PutChar(0x0A); //结尾发送回车换行
// }
counter=0;
for(int i=0;i<1000;i++)
for(int k=0;k<100;k++)
delay10us;
// __bis_SR_register(GIE);
TACTL |=MC_2; //再开定时器
}
}
#pragma vector=TIMER0_A1_VECTOR
__interrupt void Timer0_A1(void)
{
switch (__even_in_range(TA0IV, 10)) // Efficient switch-implementation
{
case 2:
fCounter++; //捕获计数
TACCTL1 &=~CCIFG;
//P1OUT^=BIT0;
break; // TA0CCR1 used
case 4:
break; // TA0CCR2 not used
case 10:
TACTL &=~MC_2;//Stop timer0
P1OUT^=BIT0; //LED指示
TAR =0xFC18;//重装计数值
mark=1; //1ms定时到标记
break;
}
}
问题:1、1ms溢出中断中停止计数器一句TACTL &=~MC_2;加上后为什么我的1ms定时成为1s了?
2、测量误差很大,20K以内还好,频率越高则也大,有何改良方法?
串口显示无问题。
此帖出自
小平头技术问答
TACTL &=~MC_2
switch语句用的。。。
一周热门 更多>