< >
Home » Arduino内置教程 » Arduino内置教程-模拟-使光滑

Arduino内置教程-模拟-使光滑

使光滑

这个程序重复读取一个模拟输入,分析一个运行均值,并且打印到电脑。这个例子用在你想使跳动的不规则的传感值变得光滑的时候,示范了怎么用保存数组。

硬件要求

  • Arduino or Genuino 开发板
  • 10k ohm 电位计

电路

请输入图片描述

把电位计的一个引脚连接到5V,中间引脚连接到模拟引脚A0,最后的引脚连接到地。

原理图

请输入图片描述

样例代码

下面的代码顺序保存10个模拟引脚的读取值,一个接一个放进一个数组里。每一次有新的值,把所有值加起来,然后取平均值,把这个平均值用作顺滑输出的数据。因为这种平均每次加一个新的值到数组里(好过一次等够10个新值),分析运行的均值之间并没有滞后时间。

改变数组的大小,通过改变 numReadings 为一个更大的值将会使保存数据变得比之前光滑。

/*

  Smoothing

  Reads repeatedly from an analog input, calculating a running average
  and printing it to the computer.  Keeps ten readings in an array and
  continually averages them.

  The circuit:
    * Analog sensor (potentiometer will do) attached to analog input 0

  Created 22 April 2007
  By David A. Mellis  <dam@mellis.org>
  modified 9 Apr 2012
  by Tom Igoe
  http://www.arduino.cc/en/Tutorial/Smoothing

  This example code is in the public domain.


*/


// Define the number of samples to keep track of.  The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input.  Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.
const int numReadings = 10;

int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

int inputPin = A0;

void setup() {
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {
  // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = analogRead(inputPin);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits
  Serial.println(average);
  delay(1);        // delay in between reads for stability
}

[Get Code]

更多

  • array
  • if
  • for
  • serial
  • AnalogInOutSerial - 读取一个模拟输入引脚,按比例划分读数,然后用这个数据来熄灭或者点亮一个LED灯
  • AnalogInput - 用电位计来控制LED灯闪烁
  • AnalogWriteMega - 永一个Arduino或者Genuino Mega开发板来使12个LED灯一个接一个逐渐打开和熄灭
  • Calibration - 定义期望中的模拟传感值的最大值和最小值
  • Fading - 用模拟输出(PWM引脚)来使LED灯变亮或者变暗

纠错,疑问,交流: 请进入讨论区点击加入Q群

获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


标签: arduino内置教程, arduino使光滑