Dear Community,
I'm trying to do a project using Arduino to collect illuminance values from a light meter and then calculate the average value of all the data.
In my code, I tried to store the collected illuminance values in a array called LuxValue. All the stored data can be printed when running the LuxReading() function. However, when I tried to calculate the average number, the data stored in the array just disappeared except the last one (LuxValue[4]), so the average value cannot be calculated correctly.
Any advice will be appreciated. Thanks in advance.
Here is the data displayed in the serial monitor:
I received: 611.50 lux // data stored in LuxValue[] array and printed when running the LuxReading()
I received: 537.00 lux
I received: 498.30 lux
I received: 458.60 lux
I received: 444.50 lux
Misson Completed!
0.00 // trying to read the LuxValue[] in the AverageLux() function, but data are missing
0.00
0.00
160.20
444.50
Sum: 604.70
Average Illuminance: 120.94
Here is my code:
char receivedChars[13];
char luxChars[5];
float LuxValue[5]; //measurement points
int b = 0; //variable for multiple measurement points - LuxValue array
void setup()
{
Serial.begin(9600);
Serial1.begin(9600,SERIAL_7E1); //according to the light meter communication method
}
void loop()
{
LuxReading(); // Call LuxReading Function
delay(500); // if I delete this delay code, it won't work. So it seems it takes some time to receive the data
if (b == 5) // Calculate Average
{
Serial.println(" Misson Completed!");
delay(1000);
AverageLux();
b = 0;
}
}
void LuxReading() //Lux Reading Function
{
int ndx = 0; //variable for receivedChars array
int a = 0; //variable for luxChars array
while (Serial1.available() > 0) //when press the D-OUT button of the light meter, read data
{
char c = Serial1.read(); // store all received data into array
if (c != '\n')
{
receivedChars[ndx] = c;
ndx++;
}
else
{
Serial.print("I received: "); // print received data on serial monitor
for (int i=6; i<=10; i++)
{
luxChars[a] = receivedChars[i];
a++;
}
LuxValue[b] = atof(luxChars); //convert char into float and store the lux value in LuxValue Array
Serial.print(LuxValue[b]);
b++;
Serial.println(" lux"); // print illuminance unit
}
}
}
void AverageLux() //Average illuminance calculation
{
float sum = 0;
float averageLux;
for (int i=0; i<=4; i++)
{
sum += LuxValue[i] ;
Serial.println(LuxValue[i]); //print data stored in LuxValue array.The serial monitor shows the data are missing except the last one
}
averageLux = sum / 5;
Serial.print("Sum: ");
Serial.println(sum); // print average illuminance value of measurement points
Serial.print("Average Illuminance: ");
Serial.println(averageLux); // print average illuminance value of measurement points
}