這篇文章主要介紹了使用UART與PC通信實現msp430g2553單片機超聲波測距示例,需要的朋友可以參考下
適用於msp430g2553單片機 使用到了hc-sr04超聲測距模塊,使用UART與PC通信。
代碼如下:
#include
long current_time;//最近一次測得時間
/*MyPro*/
#define LED_1 BIT0
#define SW_2 BIT3
#define TA1_1 BIT2 //TA0.1 HC-SR04 Echo
#define TRIG BIT4 //HC-SR04 Trig
#define ACCU_GRD 7 //Accuracy Grade "xxx.x"+' '
#define MIN_UNIT_TO1M 1000 //1 m to 1 mm
/*TIMER0*/
#define SOUR_CLK 1045000
#define DIV_CLK_1 1
#define SYS_CLK_SIG_1 SOUR_CLK/DIV_CLK_1
#define DISTANCE 45//dm
#define TIMER_RIG_MAX 0xffff
#define MAX_TIME_1 DISTANCE*2/34*SYS_CLK_SIG_1
#ifdef MAX_TIME_1
#define SYS_CLK SYS_CLK_SIG_1
#endif
#define UART_TXD BIT2
void init_timer1()
{
P2SEL |= TA1_1; //TA1.1 CCI1B be used
P2DIR &= ~TA1_1;
TA1CTL = MC_0 + TASSEL_2; //TimerA_0 stop mode,clock=1Mhz
TA1CCTL1 = CCIE + SCCI + CCIS_1 + SCS + CAP + CM_2; //TA0CC1 capture mode + down edge
}
/*UART*/
void init_uart() //USCI 初始化函數
{
UCA0CTL1 |= UCSWRST; //初始化串口寄存器
UCA0CTL1 |= UCSSEL_2; //選擇子系統時鐘 1.045MHz
UCA0BR0 = 0x6d; //波特率為9600
UCA0BR1 = 0x00;
P1SEL |= UART_TXD;
P1SEL2 |= UART_TXD;
P1DIR |= UART_TXD; //將P1.2設為第二功能
UCA0CTL1 &= ~UCSWRST; //初始化結束
}
long cal_distance() //通過測得時間計算距離
{
return (long)((340*(0.5000*current_time/SYS_CLK)*MIN_UNIT_TO1M));
}
void delay() //粗略延遲
{
unsigned char i,j;
for(i=124;i>0;i--)
for(j=8;j>0;j--);
}
static char * translater(long distance) //將測得的距離以字符串形式存儲
{
static char trans[ACCU_GRD];
int i;
long f;
trans[0]=' ';
if(distance)
for(i=1,f=MIN_UNIT_TO1M;i
{
if(i==4)
{
trans[i] = '.';
continue;
}
trans[i] = '0'+ distance/f;
distance %= f;
f /= 10;
}
trans[ACCU_GRD-1] = ' ';
return trans;
}
void once_pro() //發一次超聲波
{
if(TA1CCTL1 & COV)
TA1CCTL1 &= ~COV;
if(!(P1IN & BIT3))
{
TA1R = 0;
P1OUT |= TRIG; //Trig 10 us 高電平
_EINT();
TA1CTL |= MC_2; //continue mode
P1OUT &= ~TRIG;
P1OUT |= LED_1;
while(TA1CCTL1 & CCIFG); //等待 捕捉中斷結束
}
else
{
P1OUT &= ~LED_1;
_DINT();
}
}
void uart_txstring(char *string) //UART_TX 發送一個串
{
int i=0;
while(string[i++])
{
switch (i) //過濾無效 '0'
{
case 1:if(string[i]=='0') continue;
case 2:if(string[i]=='0'&&string[i-1]=='0') continue;
}
UCA0TXBUF = string[i];
delay();
}
}
/*UART_ISR*/
#pragma vector = USCIAB0TX_VECTOR
__interrupt void usci_txdistance() //向 PC 發送 測得的距離
{
uart_txstring("nr");
uart_txstring(" Current ");
uart_txstring(" distance: ");
uart_txstring(translater(cal_distance()));
uart_txstring(" cm");
IE2 &= ~UCA0TXIE;
}
/*TIMER0_INT_ISR*/
#pragma vector = TIMER1_A1_VECTOR
__interrupt void capture()
{
current_time = TA1CCR1;
TA1CTL &= ~MC_2;
TA1CCTL1 &= ~CCIFG; //清CC1中斷標志位
IE2 |= UCA0TXIE;
}
/*Main*/
void main()
{
WDTCTL = WDTPW + WDTHOLD; //關狗
DCOCTL = 0;
BCSCTL1 = CALBC1_1MHZ;
DCOCTL = CALDCO_1MHZ;
P1OUT = 0;
P2OUT = 0;
P1REN |= SW_2;
P2REN |= TA1_1;
P1OUT |= SW_2;
P1DIR &= ~SW_2;
P1DIR = TRIG + LED_1;
init_timer1();
init_uart();
while(1)
{
int c = 8;
while(c--)
delay();
if(TA1CCTL1 & CCIFG)
TA1CCTL1 &= ~CCIFG;
once_pro();
}
}
注:更多精彩文章請關注三聯編程教程欄目。