gpt4 book ai didi

c++ - Arduino HC-SR04 传感器,平均数据

转载 作者:行者123 更新时间:2023-11-30 02:49:00 26 4
gpt4 key购买 nike

我正在尝试使用根据与超声波传感器的距离计算出的平均值来控制 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;
}

最佳答案

您只需要更改您的代码,以便它在 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;
}

关于c++ - Arduino HC-SR04 传感器,平均数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21639725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com