我正在尝试通过为该位置分配1来使传感器扫描并标记对象。位置从30 60 90 120 150 [0 0 0 0 0]开始。然后,我想将其更改为与内存(tempArray与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);
}
答案 0 :(得分: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
//
}
祝你好运!