我正在尝试控制和LED的平均值,计算距离超声波传感器的距离。我对数据进行了平均,但是从加电开始就是连续的。我想在每十次读数后重新计算平均值。任何人都可以告诉我需要改变什么来重新计算平均每10个值而不是计算一个平均值?
const int TrigPin = 8;
const int EchoPin = 9;
const int LedPin = 13;
const int numReadings = 5;
long Duration = 0;
int readings[numReadings];
int index = 0;
int total = 0;
int average = 0;
void setup() {
Serial.begin(9600);
pinMode(LedPin, OUTPUT);
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}
void loop() {
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
Duration = pulseIn(EchoPin, HIGH);
long Distance_mm = Distance(Duration);
//Serial.print("Distance = ");
//Serial.print(Distance_mm);
//Serial.println(" mm");
total= total - readings[index];
readings[index] = analogRead(EchoPin);
total = total + readings[index];
index = index + 1;
if (index >= numReadings)
index = 0;
average = total / numReadings;
Serial.print("Dist_avg = ");
Serial.print(average);
Serial.println("mm");
delay(100);
if (average > 400)
{
digitalWrite(LedPin, HIGH); // turn the LED on (HIGH is the voltage level)
}
else
{
digitalWrite(LedPin, LOW); // turn the LED off by making the voltage LOW
}
}
long Distance(long time)
{
long DistanceCalc;
DistanceCalc = ((time /2.9) / 2);
return DistanceCalc;
}
答案 0 :(得分:3)
你只需要更改你的代码,以便它计算index == 10时的平均值。如果你将numReadings改为10,你可以尝试这样的代码:
void loop(){
...
//total= total - readings[index];
//you don't need the array here anymore
//readings[index] = analogRead(EchoPin);
//total = total + readings[index];
total = total + analogRead(EchoPin);
index = index + 1;
if (index >= numReadings)
{
index = 0;
average = total / numReadings;
Serial.print("Dist_avg = ");
Serial.print(average);
Serial.println("mm");
delay(100);
if (average > 400)
digitalWrite(LedPin, HIGH); // turn the LED on (HIGH is the voltage level)
else
digitalWrite(LedPin, LOW); // turn the LED off by making the voltage LOW
total = 0;
}
答案 1 :(得分:0)
您想要在每次阅读后平均最后十个读数,或者每10个读数计算平均值。 在第一种情况下,你需要一个&#34;旋转阵列&#34;,在第二种情况下你不需要一个数组,只需将总数设置为零,计算读数,将读数添加到总数,然后每次计数达到10时,输出平均值并再次将总数设置为零。
答案 2 :(得分:0)
只需添加此链接作为参考,即告知您不应该平均声纳数据。 http://forum.arduino.cc/index.php/topic,20920.0.html