声纳#

初始化声纳类#

使用以下构造函数创建 Range Finder:

sonar 构造函数在指定的三线端口中创建一个 sonar 对象。

范围

描述

端口

测距仪连接的三线端口“对”,可以是 Brain 上的端口,也可以是 3 线扩展器
**注意:**测距仪使用两个相邻的三线端口。这些端口对分别是 A/B、C/D、E/F 和 G/H。输入端口对作为参数时,请使用端口对的首字母,例如:“Brain.ThreeWirePort.A” 指的是 a/b 对。

必须先创建 Brain3-Wire Expander,然后才能使用 sonar Class 构造函数创建对象。

// Create the Brain.
brain Brain;
// Construct a Range Finder "Sonar" with the
// sonar class.
sonar Sonar = sonar(Brain.ThreeWirePort.A);

当引用 sonar 类方法时,此 API 文档中的所有后续示例中都将使用此 Sonar 对象。

类方法#

距离()#

distance(units) 方法返回测距仪当前探测到的物体距离。如果在探测范围内未探测到任何物体,测距仪将返回一个较大的正数。

参数

描述

单位

有效的 distanceUnit

**返回:**表示测距仪测量的距离的双精度数。

// Get the Range Finder distance in millimeters.
double value = Sonar.distance(mm);

// Print the current distance detected by the Range Finder to the
// Brain's screen.
Brain.Screen.print(value);

找到对象()#

foundObject() 方法检查测距仪是否在 0 - 1000 毫米范围内检测到物体。如果检测到的物体距离小于 1000 毫米,测距仪将返回 true。

**返回:**如果测距仪检测到物体,则返回 true。如果没有检测到,则返回 false

// Check if an object is 1000mm or closer to the Range Finder.
if (Sonar.foundObject()){
    // Print to screen on the brain that an object was found.
    Brain.Screen.print("object found");
}

设置最大值()#

setMaximum(distance, units) 方法设置 foundObject() 方法将返回 true 的最大距离。

参数

描述

距离

表示测距仪能够找到物体的最大距离的双精度数。

单位

有效的 distanceUnit

**返回:**无。

已更改()#

当 Range Finder 的值发生改变时,changed(callback) 方法会运行回调函数。

参数

描述

打回来

当 Range Finder 的值发生变化时运行的回调函数。

**返回:**无。

// Define the sonarChanged function with a void return type,
// showing it doesn't return a value.
void sonarChanged() {
  // The Brain will print that the value detected by the
  // Range Finder changed on the Brain's screen.
  Brain.Screen.print("Range Finder value changed");
}

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();

  // Run sonarChanged when the value of the
  // Range Finder changes.
  Sonar.changed(sonarChanged);
}