learing:examples:smoothing
Smoothing(平滑处理)
这个例子演示了不断读取模拟输入的数据,计算连续数据的平均值并且显示到电脑上。这个例子对于平滑不规则的跳跃性的输出值很有用,同样也演示了数组的用法。
ALPHA MEGA328-U核心
硬件
搭建电路
- ALPHA MEGA328-U模块插入并行扩展板1号槽位。
- ALPHA 电位器模块插入并行扩展版2号槽位。
- USB线连接计算机与ALPHA MEGA328-U。
代码
/* Smoothing 连续读取模拟输入值,计算连续数据的平均值并且显示在电脑上。 把十个数据存到数组中不断地计算他们的平均值。 定义数字的样本并且持续监测,数值越高,平滑的数据就越多,对应输入端的数据输出就会越慢。 使用常量而不是变量来决定数组的大小 */ const int numReadings = 10; int readings[numReadings]; // 读取模拟量 int index = 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[index]; //读取传感器数据 readings[index] = analogRead(inputPin); //添加到总数 total= total + readings[index]; // 增加到数组的下一个位置 index = index + 1; //如果到了数组结束的地方 if (index >= numReadings) // 从头开始 index = 0; // 计算平均值: average = total / numReadings; // 作为ASCII数据发送到电脑 Serial.println(average); delay(1); // 延时 }
ALPHA 8F328D-U核心
硬件
搭建电路
代码
MangoII
硬件要求
OCROBOT控制器 |
电位器 |
导线 |
连接电位器中间脚到模拟口A0,另外两个连接到+5V和GND
代码
下面的代码一个一个的连续存储10个从模拟口读取到的数据到数组。每得到一个新的值,所有数据的总数就被产生和分开,产生一个会被用来平滑无关数据的平均值。因为这个平均值发生在每次新的值被加到数组中(而不是等待10个新的数据),所以计算连续数据的平均值没有时间间隔。
改变使用的数组的大小,通过改变“numReadings”变量的大小,更大的值会平滑更多采集到的数据。
/* Smoothing 连续读取模拟输入值,计算连续数据的平均值并且显示在电脑上。 把十个数据存到数组中不断地计算他们的平均值。 */ // 定义数字的样本并且持续监测,数值越高,平滑的数据就越多,对应输入端的数据输出就会越慢。 //使用常量而不是变量来决定数组的大小 const int numReadings = 10; int readings[numReadings]; // 读取模拟量 int index = 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[index]; //读取传感器数据 readings[index] = analogRead(inputPin); //添加到总数 total= total + readings[index]; // 增加到数组的下一个位置 index = index + 1; //如果到了数组结束的地方 if (index >= numReadings) // 从头开始 index = 0; // 计算平均值: average = total / numReadings; // 作为ASCII数据发送到电脑 Serial.println(average); delay(1); // 延时 }
learing/examples/smoothing.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1