【发布时间】: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