模拟部分-信号平滑

本例中程序不断的读取模拟信号值,计算平均值,并且将平均值输出到电脑。本例所展示的方法能够平滑飘忽不定或忽上忽下的模拟信号。例子中也展示了使用数组存储数据的方法。

硬件需求
Arduino板
clip_image00210kΩ电位器
连接线

电路
将电位器两侧的引脚分别连接到5V和GND,将中间引脚连接到A0。

原理图
clip_image004

代码

下列代码按照次序存储10次读取值到数组,将这十个值求和,并且求取平均数,得到的平均数会起到平滑作用。由于计算平均值的时刻是每次添加新的传感器值时(每增加一个就计算一次)。因此,每次代码执行的时间都是相同的。

你可以增加数组的容量,来达到更好的平滑。

/*

信号平滑

不断读取模拟信号值、求取平均值后输出到电脑。将10次数据存储到数组并且不断计算平均数。

电路连接:
* 模拟信号传感器(电位器即可)连接到A0

代码是公开的.
*/

// 保存的数据个数越多,平滑效果就越好,不过每次计算时间就越长。
//注意:应该使用常量来定义数组容量,而非变量
// 我们且将元素个数限制为10
const int numReadings = 10;

int readings[numReadings];      // 存储数组
int readIndex = 0;              // 当前读到的位置(数组下标)
int total = 0;                  // 和
int average = 0;                // 平均值

int inputPin = A0;

void setup() {
// 初始化和电脑的串口连接:
Serial.begin(9600);
// 初始化数组,用0填充:
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0;
}
}

void loop() {
// 总和扣除上次的值:
total = total - readings[readIndex];
// 从传感器读新值:
readings[readIndex] = analogRead(inputPin);
// 将新值加到总和:
total = total + readings[readIndex];
// 下表加一:
readIndex = readIndex + 1;

// 如果在数组的最后
if (readIndex >= numReadings) {
// 从头开始:
readIndex = 0;
}

// 计算平均值:
average = total / numReadings;
// 作为ASCII字符传到电脑
Serial.println(average);
delay(1);        // 为稳定,延迟1毫秒。
} 
0
分享到:

评论0

请先

本站资料配套硬件销售店铺:天猫店ultirobot.tmall.com 、三冠淘宝店zhongbest.taobao.com
没有账号? 忘记密码?