while (1) {
// 获取当前时间作为起始时间
clock_gettime(CLOCK_MONOTONIC, &start_time); // 获取起始时间
for (i = 0; i < 2; i++) { // 轮询两个传感器
Timeout = 0;
dataReady = 0;
// 检查数据是否准备好
error = VL53L1X_CheckForDataReady(Devs[i], &dataReady);
if (error != 0) {
printf("Error checking data readiness for sensor %d\n", i);
continue; // 如果检查失败,跳过这个传感器
}
// 等待数据准备就绪或超时
while (dataReady == 0 && Timeout == 0) {
usleep(1000); // 每次等待 1 毫秒,防止 CPU 空转
clock_gettime(CLOCK_MONOTONIC, ¤t_time); // 获取当前时间
// 检查是否超时
unsigned long elapsed_time_ms = (current_time.tv_sec - start_time.tv_sec) * 1000 + (current_time.tv_nsec - start_time.tv_nsec) / 1000000;
if (elapsed_time_ms >= MAX_WAIT_TIME_MS) {
Timeout = 1; // 超时标志
printf("Timeout waiting for data on sensor %d\n", i);
} else {
// 如果还没超时,继续检查数据准备状态
error = VL53L1X_CheckForDataReady(Devs[i], &dataReady);
if (error != 0) {
printf("Error checking data readiness for sensor %d\n", i);
break;
}
}
}
if (Timeout == 0) {
// 数据准备好,清除中断并读取结果
error = VL53L1X_ClearInterrupt(Devs[i]);
if (error != 0) {
printf("Error clearing interrupt for sensor %d\n", i);
continue;
}
error = VL53L1X_GetDistance(Devs[i], &Distance);
if (error != 0) {
printf("Error getting distance for sensor %d\n", i);
continue;
}
error = VL53L1X_GetRangeStatus(Devs[i], &RangeStatus);
if (error != 0) {
printf("Error getting range status for sensor %d\n", i);
continue;
}
// 打印当前传感器的数据
printf("sensor %d: distance = %5d, status = %2d\n", i, Distance, RangeStatus);
}
}
// 超时处理:如果超时发生,重置所有传感器
if (Timeout == 1) {
if (set_gpio_value(gpio_set[0], 0) < 0) {
printf("Failed to set XSHUT GPIO to high\n");
return false;
if (set_gpio_value(gpio_set[1], 0) < 0) {
printf("Failed to set XSHUT GPIO to high\n");
return false;
}
}
}
// 触发下次测距
for (i = 0; i < 2; i++) {
error = VL53L1X_ClearInterrupt(Devs[i]); // 清除中断
if (error != 0) {
printf("Error clearing interrupt for sensor %d\n", i);
}
// 第一次测量时跳过(可以根据需求调整)
if (first_range) {
error = VL53L1X_ClearInterrupt(Devs[i]);
first_range = 0; // 设置为非第一次测量
}
}
usleep(1000); // 等待一段时间再进行下次操作
}
这是运行时候的结果,不知道为什么这里无论是sensor0还是senser1都是同一个传感器的数据,我用手挡住另外一个传感器都没有反应的,只有其中一个有反应并有数据输出