#define PIN_TRIG 3
#define PIN_ECHO 2
void setup() {
Serial.begin(115200);//设置串口波特率
pinMode(PIN_TRIG, OUTPUT); //设置PIN_TRIG为输出口
pinMode(PIN_ECHO, INPUT);//设置PIN_ECHO为输入口
}
void loop() {
// Start a new measurement:
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10); //让PIN_TRIG端口持续10微妙高电平输出
digitalWrite(PIN_TRIG, LOW);
// Read the result:
int duration = pulseIn(PIN_ECHO, HIGH);//设置PIN_ECHO为高电平
Serial.print("Distance in CM: ");
Serial.println(duration*0.034/2); //距离= 时间×速度
delay(1000);
}