C串口读取并计算平均值 [英] C Serial Port read and calculate average

查看:85
本文介绍了C串口读取并计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个串口程序可以从ttyUSB端口读写,我想要一个逻辑来读取ttyUSB中的no值端口并计算该值的平均值



我有一个重量板,只要有重量就会连续发送数据,我需要获取数据和计算平均值并显示它







谢谢

shan

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

推荐答案

根据您对Richard的评论,您已经将数据作为字符串获取。你需要做的是

(1)将字符串转换为数字

(2)保存该号码

(3)增加你的指向下一个字符串的索引

(4)重复步骤1 - 3直到你有足够的样本

(5)将N个样本加在一起然后除以N.



从您的示例数据中,请考虑以下因素:



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:

// 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;







注意,你可以避免将转换后的数字存储到values数组中,而只是在使用atof的循环之前清除总数,并将atof的结果添加到total而不是存储它。这将具有不需要值数组的优点。它的缺点是使错误检查(我没有做过)变得更加棘手。您可以将atof的返回值分配给临时值,在将其添加到总数之前确保其有效数字,并递增另一个存储成功转换数字的计数器。




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.


这篇关于C串口读取并计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆