Reputation: 73
I have a class where I have 2 functions as below;
// Function to calculate the sum and average temperature
float read_samples(float *data, int num_samples)
{
float sum = 0.0;
float average = 0.0;
for(int i = 1; i < num_samples; i++ ) {
data[i] = temperature.read();
sum = sum + data[i];
wait(1);
}
average = sum / (num_samples - 1);
return average;
}
// Main Function that is called on running the application
int main()
{
int num_samples = 12 / 1;
float data[num_samples];
//sw.fall(read_samples(data, num_samples));
while(1) {
wait(12);
float result = read_samples(data, num_samples);
lcd.printf("%.2f\n", result);
//data[0];
}
}
When I call the "wait(12);" method in Main, I want the code to at the same time to go execute the "read_samples" method while waiting, and when the "read_samples" is done return the value computed, then go ahead to display the computed result in the Main function. The computation should be during the 12 seconds while waiting.
However, what is happening right now is that during the 12 seconds while waiting, no execution is carried out, so after waiting for 12 seconds it goes to call the "read_samples" method and carries out execution for another 11 seconds. So the total time spent to display the next result is (12 + 11) 23 seconds. Please, how do I write my code to execute the "read_samples" method during the 12 seconds wait?
Upvotes: 0
Views: 811
Reputation: 27322
You can run the read_samples
in a separate thread. E.g.:
static float average = 0.0f;
// Function to calculate the sum and average temperature
void read_samples()
{
int num_samples = 12 / 1;
float data[num_samples];
float sum = 0.0;
for(int i = 1; i < num_samples; i++ ) {
data[i] = temperature.read();
sum = sum + data[i];
wait(1);
}
average = sum / (num_samples - 1);
}
// Main Function that is called on running the application
int main()
{
//sw.fall(read_samples(data, num_samples));
while(1) {
Thread sampleThread;
sampleThread.start(&read_samples);
wait(12);
lcd.printf("%.2f\n", result);
//data[0];
}
}
You'll want to guard access to the average
through a Mutex.
Upvotes: 0