const int trigPin = 25; // Trigger Pin of Ultrasonic Sensor const int echoPin = 28; // Echo Pin of Ultrasonic Sensor void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(9600); // Starting Serial Terminal } void loop() { long duration, inches, cm; digitalWrite(trigPin, LOW);//clears the trigger pin condition delayMicroseconds(2); digitalWrite(trigPin, HIGH); //sets the trigger pin HIGH (ACTIVE) for 10 us delayMicroseconds(10); digitalWrite(trigPin, LOW); //read the echoPin,return the sound wave travel time in us duration = pulseIn(echoPin, HIGH); // us to cm cm = microsecondsToCentimeters(duration); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } long microsecondsToCentimeters(long microseconds) { //speed of sound wave divided by 2 (go and back) return microseconds * 0.034 / 2; } 把距离打包成可调取的子函数
时间: 2024-04-11 22:27:04 浏览: 133
C/C++ 中const关键字的用法小结
您可以将距离计算封装为一个可调用的子函数。以下是一种实现方式:
```cpp
const int trigPin = 25; // 触发引脚
const int echoPin = 28; // 回声引脚
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600); // 启动串口终端
}
void loop() {
long duration, inches, cm;
cm = getDistance(); // 调用子函数获取距离
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long getDistance() {
digitalWrite(trigPin, LOW); // 清除触发引脚状态
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH); // 读取回声引脚,返回声波行程时间(单位:微秒)
return microsecondsToCentimeters(duration); // 转换为厘米并返回距离值
}
long microsecondsToCentimeters(long microseconds) {
return microseconds * 0.034 / 2; // 声速的一半(来回)
}
```
通过将距离计算封装为 `getDistance()` 子函数,您可以在 `loop()` 循环中直接调用它来获取距离,并且代码更加模块化和可读性更强。
阅读全文