msp430超声波测距代码
时间: 2023-07-09 13:34:59 浏览: 161
下面是 MSP430 超声波测距的代码,仅供参考:
```c
#include "msp430g2553.h"
#define TRIGGER BIT0 //P1.0
#define ECHO BIT1 //P1.1
void delay_us(unsigned int us)
{
__delay_cycles(us);
}
void delay_ms(unsigned int ms)
{
__delay_cycles(1000*ms);
}
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // stop WDT
P1DIR |= TRIGGER; //P1.0 as output
P1DIR &= ~ECHO; //P1.1 as input
P1OUT &= ~TRIGGER; //P1.0 output low
while (1)
{
unsigned int distance = 0;
unsigned int time = 0;
P1OUT &= ~TRIGGER; //P1.0 output low
delay_us(2);
P1OUT |= TRIGGER; //P1.0 output high
delay_us(10);
P1OUT &= ~TRIGGER; //P1.0 output low
while(!(P1IN & ECHO)); //wait for the rising edge
TACCR0 = 0;
TACTL = TASSEL_2 + MC_2; //SMCLK, continuous mode
while(P1IN & ECHO);
TACTL = MC_0; //stop the timer
time = TAR;
distance = time / 58; //calculate the distance
delay_ms(1000); //wait for 1s
}
}
```
这段代码使用 MSP430G2553 控制器进行超声波测距,将超声波测距的距离计算公式 `distance = time / 58` 写在了代码中。具体的使用方法可以参考代码中的注释。
阅读全文