Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all,

I have a serial port program to read and write from a ttyUSB port, i want a logic to read a no of values from the ttyUSB port and to calculate the average for that values

I am having a weight board it sends the data continiuosly whenever the weight is there, i need to get the data in and calculate the average and to display it



Thanks
shan
Posted
Comments
Richard MacCutchan 27-Nov-13 5:29am    
And what exactly is your problem?
shan bala 27-Nov-13 6:25am    
hi richard,

I am having a serial port user space application to read the weight data from the weight machine, for that i have a buffer of size 100 and print the data byte by byte which read from the weight machine i got the output as follows

buffer[0] = 3
buffer[1] = .
buffer[2] = 0
buffer[3] = 9
The actual data is 3.09 which contains 4 bytes and a '\0', the output of the weight machine ascii string and this data is continuously sent by the weight machine

My problem is, i need to take 5-10 values and calculate the average for that, i want the logic on how can i make that 4 byte data as a single value for example:-
I am printing this buffer values as a %c
buffer[0] = 3
buffer[1] = .
buffer[2]= 0
buffer[3]= 9

buffer[5]= 3
buffer[6]= .
buffer[7]= 0
buffer[8]= 9
average= 3.09+3.09/2-----> This is what i want to do

1 solution

Based on your comment to Richard, you've already got the data as strings. What you need to do is
(1) Convert a string to a number
(2) Save this number
(3) Increment your Index to point at the next string
(4) Repeat steps 1 - 3 until you have enough samples
(5) Add N samples together then divide by N.

From your example data, consider the following:

C++
// max number of values to average and the index of current one
int N=5, i;

// space for 5 vales
double values[5];

double total, avg;

for (i=0; i<N; i++)
{
    values[i] = atof( &buffer[i*5] );
}

total = 0;
for (i=0; i<N; i++)
    total += values[i];

avg = total / N;



Note, you could avoid storing the converted numbers into the values array, instead simply clearing the total before the loop that uses atof and adding the result of atof to the total instead of storing it. This would have the advantage of not requiring the values array. It would have the disadvantage of making error checking (which I've not done) a litle trickier. You could assign the return of atof to a temporary value, ensuring that its a valid number before adding it to the total and incrementing another counter that stored the number of successfully converted numbers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900