Arduino比较数组的权重

问题描述 投票:0回答:1

我试图让传感器扫描并通过为该位置指定1来标记对象。位置为30 60 90 120 150 [0 0 0 0 0]。然后我想把那个aray和它与内存(tempArray vs memArray)进行比较并决定转向哪种方式。基本上避免障碍,关于如何使用数组实现这一点的任何建议?

void scan() {
servo.write(30);
delay(350);
rScan = echodis();
 if (rScan > distanceLimit) {
tempArray[4] = 1;
  }
servo.write(60);
delay(350);
rDiagScan = echodis();
if (rDiagScan > distanceLimit) {
  tempArray[3] = 1;
  }
servo.write(90);
delay(350);
cScan = echodis();
if (cScan > distanceLimit) {
  tempArray[2] = 1;
  }
servo.write(120);
delay(350);
lDiagScan = echodis();
if (lDiagScan > distanceLimit) {
  tempArray[1] = 1;
 }
servo.write(150);
delay(350);
lScan = echodis();
if (lScan > distanceLimit) {
  tempArray[0] = 1;
}
scanCount++;

servo.write(120);
delay(350);
lDiagScan = echodis();
if (lDiagScan > distanceLimit) {
  tempArray[1] = 1;
 } servo.write(90);
delay(350);
cScan = echodis();
if (cScan > distanceLimit) {
  tempArray[2] = 1;
  }
servo.write(60);
delay(350);
rDiagScan = echodis();
if (rDiagScan > distanceLimit) {
  tempArray[3] = 1;
}
servo.write(30);
delay(350);
rScan = echodis();
if (rScan > distanceLimit) {
  tempArray[4] = 1;
}
scanCount++;
//if(scanCount = 4){
 //memset(tempArray, 0, sizeof(tempArray));
//}
//return (tempArray);




 }
arrays arduino sensor robotics
1个回答
0
投票

有很多方法可以在重复中解决这些问题,这里有一个。

这里的方法是让状态和数据驱动操作,而不是大规模重复,容易出错的代码。还要考虑在一个地方定义最小值,最大值,常数等的重要性。

#define SERVO_SETTLE_MILLIS  350
#define SERVO_STEP  30
#define SERVO_SAMPLE_LEN  5
#define OUTLIER 1
#define INLIER 0

byte scan_count = 0; // when even or 0, position starts at 30. when odd, position starts at 150.

void scan(byte* pSampleArray, const uint16_t maxDistance) {

  byte direction = scan_count % 2 == 0;
  byte servo_position = direction ? (SERVO_SAMPLE_LEN * SERVO_STEP) : 0;
  byte sample_index = direction ? SERVO_SAMPLE_LEN : -1;

  for (byte i = 0; i < SERVO_SAMPLE_LEN; i++) {

    // direction == 0 == servo position starts at 30 (initial)
    if (direction) {
      sample_index--; // e.g. 4,3,2,1,0
      servo_position += SERVO_STEP; // e.g. 30,60,90,120,150
    }
    else
    {
      sample_index++; // e.g. 0,1,2,3,4
      servo_position -= SERVO_STEP;; // e.g. 150,120,90,60,30
    }
    // position servo
    servo.write(servo_position);
    // settling time
    delay(SERVO_SETTLE_MILLIS);
    // sample = 1 if outlier, 0 otherwise
    pSampleArray[sample_index] = echodis() > maxDistance ? OUTLIER : INLIER;
  }

  scan_count++; // implies direction stepping for next call to scan.
}

当然,必须注意pSampleArray可以容纳5个样品。

你没有谈到你计划用“数组”做什么,这可能是你项目的真正内容,但是例如考虑函数foo

void foo(const uint16_t maxDistance) {
  byte sample1[SERVO_SAMPLE_LEN];
  byte sample2[SERVO_SAMPLE_LEN];
  scan(sample1, maxDistance);
  delay(1000);
  scan(sample2, maxDistance);
  //
  // process your samples
  //
}

祝好运!

© www.soinside.com 2019 - 2024. All rights reserved.