Arduino 入门教程(十) 测量超声波的速度

Potential diagram:

Arduino 入门教程(十) 测量超声波的速度

代码:

int tripPin = 13; // 传感器访问led针脚13
int echoPin = 11; // 传感器输出针脚 11
float pingTime ; // 超声波发出到传回来的时间
float speedOfSound;// 声音的速度
int targetDistance = 6; // 传感器离碰撞物体的距离
void setup() {
  Serial.begin(9600);// 开启串口通信
  pinMode(tripPin, OUTPUT); // 用于输出
  pinMode(echoPin, INPUT); // 用于读取
}
void loop() {
  digitalWrite(tripPin, LOW); // 写入低电平
  delayMicroseconds(2000);// 延迟微秒
  digitalWrite(tripPin, HIGH); // 写入高电平
  delayMicroseconds(10);
  digitalWrite(tripPin, LOW);

  pingTime = pulseIn(echoPin, HIGH); // 读取超声波的时间
  // 声音的速度 = 距离 / 时间
  // 单位转换 最后输出单位为 英里/小时
  speedOfSound = (targetDistance * 2 / pingTime * 1000000 * 3600) / 633600;
  Serial.print("The Speed of Sound is:  ");
  // 打印声音的速度
  Serial.print(speedOfSound);
  Serial.println("miles per hour");
  delay(1000);
}