I was reviewing previous questions related to my topic, I found this: Moving average in C++ with arduino
The problem I have is very similar, but I want to relize distance averages every 150 seconds from a vl6180x adafruit distance sensor.
Average the first 150 seconds, print the result, then from the second 151 to 300 print the result and have it continue averaging my code.
I tried to do the same thing that is in the link I posted with my problem and I could not compile the code (I am programming from the Arduino IDE, and I am a beginner). My goal is to reduce the signal noise with moving average. My code:
#include <Wire.h>
#include "Adafruit_VL6180X.h"
#define BUF_SIZE 15
Adafruit_VL6180X vl = Adafruit_VL6180X();
float array_calculate_avg(int * buf, int len);
int buf[BUF_SIZE] = {0};
int buf_index = 0;
float buf_avg = 0.0;
int len
void setup() {
Serial.begin(115200);
// wait for serial port to open on native usb devices
while (!Serial) {
delay(1);
}
Serial.println("Adafruit VL6180x test!");
if (! vl.begin()) {
Serial.println("Failed to find sensor");
while (1);
}
Serial.println("Sensor found!");
}
void loop() {
// Reset the index and start over.
//
if (BUF_SIZE == buf_index)
{
buf_index = 0;
}
buf[buf_index++] = vl.readRange();
buf_avg = array_calculate_avg(buf, BUF_SIZE);
Serial.print(buf_avg, 4);
delay(2000);
float lux = vl.readLux(VL6180X_ALS_GAIN_5);
Serial.print("Lux: "); Serial.println(lux);
uint8_t range = vl.readRange();
uint8_t status = vl.readRangeStatus();
if (status == VL6180X_ERROR_NONE) {
Serial.print("Range: "); Serial.println(range);
}
// Some error occurred, print it out!
if ((status >= VL6180X_ERROR_SYSERR_1) && (status <= VL6180X_ERROR_SYSERR_5)) {
Serial.println("System error");
}
else if (status == VL6180X_ERROR_ECEFAIL) {
Serial.println("ECE failure");
}
else if (status == VL6180X_ERROR_NOCONVERGE) {
Serial.println("No convergence");
}
else if (status == VL6180X_ERROR_RANGEIGNORE) {
Serial.println("Ignoring range");
}
else if (status == VL6180X_ERROR_SNR) {
Serial.println("Signal/Noise error");
}
else if (status == VL6180X_ERROR_RAWUFLOW) {
Serial.println("Raw reading underflow");
}
else if (status == VL6180X_ERROR_RAWOFLOW) {
Serial.println("Raw reading overflow");
}
else if (status == VL6180X_ERROR_RANGEUFLOW) {
Serial.println("Range reading underflow");
}
else if (status == VL6180X_ERROR_RANGEOFLOW) {
Serial.println("Range reading overflow");
}
delay(50);
float
array_calculate_avg(int * buf, int len);
{
int sum = 0;
for (int i = 0; i < len; ++i)
{
sum += buf[i];
}
return ((float) sum) / ((float) len);
}
My native language is not English. Apologies if I have gross grammatical errors :/
Your loop()
function is missing a closing brace }
right before the float array_calculate_avg(int * buf, int len);
line which, btw, also has a semicolon ;
at the end, which it shouldn't.