【问题标题】:My code wont print out the correct value for the array index 0我的代码不会打印出数组索引 0 的正确值
【发布时间】:2020-02-28 15:10:41
【问题描述】:
#include <NewPing.h>

#define SONAR_NUM 6      // Number of sensors.
#define MAX_DISTANCE 500 // Maximum distance (in cm) to ping.

NewPing sonar[SONAR_NUM] =     // Sensor object array. Each sensor's trigger pin, echo pin, and max distance to ping.
{
  NewPing(1, 2, MAX_DISTANCE),   //1 Bottom right
  NewPing(3, 4, MAX_DISTANCE),   //2 Top right
  NewPing(5, 6, MAX_DISTANCE),   //3 Bottom middle
  NewPing(7, 8, MAX_DISTANCE),   //4 Top middle
  NewPing(9, 10, MAX_DISTANCE),  //5 Bottom left
  NewPing(11, 12, MAX_DISTANCE), //6 Top left
};

int Dist;
int myDist[6];
int m;
int minIndex;
int minValue;

void setup()
{
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  }

void loop()
{
  for (uint8_t i = 0; i < SONAR_NUM; i++)   // Loop through each sensor and store results.
  {
    delay(30); // Wait 30ms between pings . 29ms should be the shortest delay between pings.
    myDist[i] = sonar[i].ping_cm(); 
  }
  math();       //go to math function
}

void math()
{
    int minIndex;
    int myDist_length = sizeof(myDist) / sizeof(myDist[0]);        //find length of array
    int minValue = myDist[minIndex];                              //min value = value from min index of array
    for(byte j = 1; j < myDist_length; j++){                     //for loop lasts length of array
    if(myDist[j] < minValue) {                                  //if loop finds out if value is smaller than previous smallest
        minValue = myDist[j];
        minIndex = j;
    }
}
//Serial.print(minValue);
//Serial.print(", ");
Serial.print(myDist[0]);
Serial.println();

}

我的代码试图从超声波传感器中查找值并将它们存储在一个数组中。它工作正常,除了当我尝试打印数组的 0 索引时,我的第一个传感器不会打印出一个值。我使用了另一个代码,传感器和接线都可以正常工作。我的猜测是我存储它的方式是错误的。我的数组的所有其他索引都从正确的传感器打印出适当的值,但数字 1 或索引 0 没有。

【问题讨论】:

  • 为什么 j 从 1 开始而不是 j=0?

标签: arrays arduino arduino-uno arduino-ide


【解决方案1】:

index 0 的输出是什么?
它是否总是相同的数字,例如0?或者,它是一个随机数?总是积极的?只是想帮你调试。

【讨论】:

  • 它始终为 0,其他索引传递正确的数字
  • 我不记得 Arduino 是否将数组元素初始化为 0。我想知道数据中的 0 来自哪里——从传感器轮询数据,或者只是初始化并且从未被覆盖。您可以手动将 [0] 值设置为一些不太可能的数字,例如 1111,看看它是否在轮询传感器后仍然保持原样?
【解决方案2】:

在 math() 函数中:

int minIndex;

应该是

int minIndex = 0;

你需要给 minIndex 一个初始值。您假设它从零开始。这不是一个安全的假设,因为它是一个局部变量。您需要将其显式设置为零。

【讨论】:

  • 我还注意到您有一个同名的全局变量。它会以零值开始,但是您隐藏了它并且从未使用它。在作用域内拥有多个同名变量通常是不明智的。这会导致所有类型的混乱。要么摆脱全局的,要么摆脱本地的。
猜你喜欢
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 2022-10-02
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多