用户工具

站点工具


ocrobot:alpha:kitone:tutorial18

Smoothing(平滑处理)

这个例子演示了不断读取模拟输入的数据,计算连续数据的平均值并且显示到电脑上。这个例子对于平滑不规则的跳跃性的输出值很有用,同样也演示了数组的用法。

ALPHA MEGA328-U核心

硬件

搭建电路

  1. ALPHA MEGA328-U模块插入并行扩展板1号槽位。
  2. ALPHA 电位器模块插入并行扩展版2号槽位。
  3. 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);           // 初始化串口通讯
  for (int thisReading = 0; thisReading < numReadings; thisReading++) // 初始化读取数据到0
    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;          // 计算平均值:
  Serial.println(average);     // 作为ASCII数据发送到电脑
  delay(1);        // 延时
}

返回上一级

ocrobot/alpha/kitone/tutorial18.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1