使用IAR实现超声波测距,但是用串口在PC机显示时是16进制显示。
#include <msp430x14x.h>
typedef unsigned char uchar;
typedef unsigned int uint;
#define CPU_F ((double)32768) //外部低频晶振32.768KHZ
#define delay_us(x) __delay_cycles((long)(CPU_F*(double)x/1000000.0))
#define delay_ms(x) __delay_cycles((long)(CPU_F*(double)x/1000.0))
#define Trig1(a) if(a==1) P1OUT |= BIT3; else P1OUT &= ~BIT3
#define RISE 1
#define FALL 0
void Delays(void);
void PutString(uchar *ptr);
void Hc_sr_Init(void);
void Hc_sr_Open(void);
uint TA_Overflow_Cnt;
unsigned int cap_new = 0; // 首次捕捉的ta0r值
unsigned int cap_old = 0; // 二次捕捉的ta0r值
char cap_N = 0; // 溢出次数
char state = 0x00;
long cap_data = 0; // 距离值
uint value = 0;
void main(void)
{
Hc_sr_Init(); //初始化定时器
WDTCTL = WDTPW + WDTHOLD; // 关狗
//初始化串口
P3SEL |= 0xC0; // P3.6,7 = USART1 TXD/RXD
ME2 |= UTXE1 + URXE1; // Enable USART1 TXD/RXD
UCTL1 |= CHAR; // 8-bit character
UTCTL1 |= SSEL0; // UCLK = ACLK
UBR01 = 0x03; // 32k/9600 - 3.41
UBR11 = 0x00;
UMCTL1 = 0x4A; // Modulation
UCTL1 &= ~SWRST; // Initialize USART state machine
IE2 |= URXIE1; // Enable USART1 RX interrupt
_EINT();
while(1)
{
Hc_sr_Open();
while (!(IFG2 & UTXIFG1));
TXBUF1 = (int)(cap_data);
Delays();
}
}
void PutString(uchar *ptr)
{
while(*ptr != '\0')
{
while (!(IFG2 & UTXIFG1)); // TX缓存空闲
TXBUF1 = *ptr++; // 发送数据
}
while (!(IFG2 & UTXIFG1));
TXBUF1 = '\n';
}
void Delays(void)
{
uchar i=20;
uint j;
while(i--)
{
j=2000;
while(j--);
}
}
void Hc_sr_Init(void)
{
/*
* P1.2 为echo引脚 捕获模式
* P1.3 为Trig 数字i/o模式
*/
P1OUT &= ~( BIT2 + BIT3 );
P1DIR |= BIT3;
P1SEL |= BIT2;
TACTL = TASSEL_2 + ID_3 + MC_2 + TACLR + TAIE;
TACCTL1 = CM_1 + SCS +CAP + CCIE + CCIS_0;
}
void Hc_sr_Open(void) //生成一个持续10us的高电平
{
Trig1(1);
__delay_cycles(40);
Trig1(0);
}
#pragma vector=TIMERA1_VECTOR
__interrupt void TIMER0_A1_ISR(void)
{
switch(TAIV)
{
case 2 :
state = TACCTL1 >> 14;
TACCTL1 &= ~CCIFG;
if( TACCTL1 & CM_1){
cap_new = TACCR1;
TACCTL1 &= ~CM_1;
TACCTL1 |= CM_2;
}else if ( TACCTL1 & CM_2){
cap_old = TACCR1;
cap_data = ( cap_old - cap_new ) * 340/2000; //转化为cm/s
TACCTL1 &= ~CM_2;
TACCTL1 |= CM_1;
}
break;
case 4: break;
case 10:
TA_Overflow_Cnt++;//溢出标志
break;
default:
break;
}
}