批量读取#

批量读取是一次性读取集线器上所有传感器值(I2C 除外)的 LynxCommand。这与其他 LynxCommand 的执行时间相同,因此可以在执行循环中节省大量时间;批量读取时,读取十个传感器的时间与读取一个传感器的时间相同(如果它们不是 I2C 且在同一个集线器上)。

在 5.4 及以上版本的 SDK 中,这一操作变得简单多了,内置的方法可以轻松访问它。下面是如何使用批量读取的 官方示例

关闭模式(Off Mode)#

这是默认设置,也是最无聊的设置;它意味着 SDK 在调用正常硬件访问方法时不会使用批量读取。

备注

批量读取仍可通过调用 LynxModule.getBulkInputData() 方法进行,但如果希望使用批量读取(我们强烈推荐),使用 AUTOMANUAL 模式更为简单。

要手动设置 OFF 模式,需要运行::

List<LynxModule> allHubs = hardwareMap.getAll(LynxModule.class);

for (LynxModule hub : allHubs) {
   hub.setBulkCachingMode(LynxModule.BulkCachingMode.OFF);
}

自动模式(Auto Mode)#

这是最简单的批量读取模式;当硬件读取重复时,会进行新的批量读取。例如:

List<LynxModule> allHubs = hardwareMap.getAll(LynxModule.class);

for (LynxModule hub : allHubs) {
   hub.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO);
}

while (opModeIsActive()) {
   // Will run one bulk read per cycle; however, if e.g.
   // frontLeftMotor.getCurrentPosition() was called again,
   // a new bulk read would be issued
   int frontLeftEncoderPos = frontLeftMotor.getCurrentPosition();
   int frontRightEncoderPos = frontRightMotor.getCurrentPosition();
   int backLeftEncoderPos = backLeftMotor.getCurrentPosition();
   int backRightEncoderPos = backRightMotor.getCurrentPosition();
}

但是,如果在一个给定的循环中多次调用同一个硬件读取,就会出现问题,例如

List<LynxModule> allHubs = hardwareMap.getAll(LynxModule.class);

for (LynxModule hub : allHubs) {
   hub.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO);
}

while (opModeIsActive()) {
   // Will run two bulk read per cycles,
   // as frontLeftMotor.getCurrentPosition() is called twice
   int frontLeftEncoderPos = frontLeftMotor.getCurrentPosition();
   int frontLeftEncoderPos2 = frontLeftMotor.getCurrentPosition();
}

总的来说,这是推荐的,因为它不太可能搞砸任何事情,并且可以不费吹灰之力就显著提高性能。在用户方面,不需要手动刷新批量读取缓存;但是,这意味着你失去了一些控制权。

手动模式(Manual Mode)#

在手动模式下,批量读取的缓存只有在手动重置后才会重置。这可能很有用,因为它是绝对减少无关读取的方法,但如果不重置缓存,就会返回陈旧的值。下面是 手动 模式的正确实现

List<LynxModule> allHubs = hardwareMap.getAll(LynxModule.class);

for (LynxModule hub : allHubs) {
   hub.setBulkCachingMode(LynxModule.BulkCachingMode.MANUAL);
}

while (opModeIsActive()) {
   // Will run one bulk read per cycle,
   // even as frontLeftMotor.getCurrentPosition() is called twice
   // because the caches are being handled manually and cleared
   // once a loop
   for (LynxModule hub : allHubs) {
      hub.clearBulkCache();
   }

   int frontLeftEncoderPos = frontLeftMotor.getCurrentPosition();
   int frontLeftEncoderPos2 = frontLeftMotor.getCurrentPosition();
}

警告

MANUAL 模式下,如果没有适当地清除缓存,就会返回过时的值。因此,如果你不太确定自己在做什么,我们建议你使用 AUTO 模式;如果没有最佳地使用 AUTO 模式,虽然 MANUAL 模式可以在一定程度上提高性能,但它发生灾难性错误的可能性较小。

小技巧

批量读取是针对每个集线器发出的,因此不一定需要同时或每次循环批量读取两个集线器。