В этой статье блога мы рассмотрим различные методы расчета среднего значения датчика в Arduino. Мы предоставим примеры кода для каждого метода, чтобы помочь вам понять и реализовать их в ваших собственных проектах. Независимо от того, являетесь ли вы новичком или опытным пользователем Arduino, это руководство предоставит вам различные подходы для эффективного расчета среднего значения датчика.
Метод 1: использование текущей суммы
Пример кода:
int sensorPin = A0;
int numReadings = 10;
int readings[10];
int index = 0;
int total = 0;
float average = 0;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Initialize the readings array
for (int i = 0; i < numReadings; i++) {
readings[i] = 0;
}
}
void loop() {
// Subtract the last reading
total = total - readings[index];
// Read from the sensor
readings[index] = analogRead(sensorPin);
// Add the new reading to the total
total = total + readings[index];
// Move to the next position in the array
index = (index + 1) % numReadings;
// Calculate the average
average = total / numReadings;
// Print the average
Serial.println(average);
// Delay for stability
delay(100);
}
Метод 2: использование подвижного массива
Пример кода:
int sensorPin = A0;
int numReadings = 10;
int readings[10];
int index = 0;
float average = 0;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Initialize the readings array
for (int i = 0; i < numReadings; i++) {
readings[i] = 0;
}
}
void loop() {
// Read from the sensor
readings[index] = analogRead(sensorPin);
// Move to the next position in the array
index = (index + 1) % numReadings;
// Calculate the sum of the readings
int sum = 0;
for (int i = 0; i < numReadings; i++) {
sum += readings[i];
}
// Calculate the average
average = sum / numReadings;
// Print the average
Serial.println(average);
// Delay for stability
delay(100);
}
Метод 3: использование экспоненциальной скользящей средней (EMA)
Пример кода:
int sensorPin = A0;
float smoothingFactor = 0.1;
float average = 0;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
}
void loop() {
// Read from the sensor
int sensorValue = analogRead(sensorPin);
// Calculate the average using EMA formula
average = (sensorValue * smoothingFactor) + (average * (1 - smoothingFactor));
// Print the average
Serial.println(average);
// Delay for stability
delay(100);
}
В этой статье мы рассмотрели несколько методов расчета среднего значения датчика в Arduino. Мы предоставили примеры кода для каждого метода, включая использование текущей суммы, скользящего массива и экспоненциального скользящего среднего. Эти методы можно использовать в различных проектах Arduino, предполагающих обработку данных датчиков. Используя эти методы, вы можете получить точные и стабильные средние значения датчиков для ваших приложений.