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

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

    电路
    模拟-使光滑 - 图1
    把电位计的一个引脚连接到5V,中间引脚连接到模拟引脚A0,最后的引脚连接到地。
    原理图
    模拟-使光滑 - 图2
    样例代码
    下面的代码顺序保存10个模拟引脚的读取值,一个接一个放进一个数组里。每一次有新的值,把所有值加起来,然后取平均值,把这个平均值用作顺滑输出的数据。因为这种平均每次加一个新的值到数组里(好过一次等够10个新值),分析运行的均值之间并没有滞后时间。
    改变数组的大小,通过改变 numReadings 为一个更大的值将会使保存数据变得比之前光滑。

    1. /*
    2. Smoothing
    3. Reads repeatedly from an analog input, calculating a running average
    4. and printing it to the computer. Keeps ten readings in an array and
    5. continually averages them.
    6. The circuit:
    7. * Analog sensor (potentiometer will do) attached to analog input 0
    8. Created 22 April 2007
    9. By David A. Mellis <dam@mellis.org>
    10. modified 9 Apr 2012
    11. by Tom Igoe
    12. http://www.arduino.cc/en/Tutorial/Smoothing
    13. This example code is in the public domain.
    14. */
    15. // Define the number of samples to keep track of. The higher the number,
    16. // the more the readings will be smoothed, but the slower the output will
    17. // respond to the input. Using a constant rather than a normal variable lets
    18. // use this value to determine the size of the readings array.
    19. const int numReadings = 10;
    20. int readings[numReadings]; // the readings from the analog input
    21. int readIndex = 0; // the index of the current reading
    22. int total = 0; // the running total
    23. int average = 0; // the average
    24. int inputPin = A0;
    25. void setup() {
    26. // initialize serial communication with computer:
    27. Serial.begin(9600);
    28. // initialize all the readings to 0:
    29. for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    30. readings[thisReading] = 0;
    31. }
    32. }
    33. void loop() {
    34. // subtract the last reading:
    35. total = total - readings[readIndex];
    36. // read from the sensor:
    37. readings[readIndex] = analogRead(inputPin);
    38. // add the reading to the total:
    39. total = total + readings[readIndex];
    40. // advance to the next position in the array:
    41. readIndex = readIndex + 1;
    42. // if we're at the end of the array...
    43. if (readIndex >= numReadings) {
    44. // ...wrap around to the beginning:
    45. readIndex = 0;
    46. }
    47. // calculate the average:
    48. average = total / numReadings;
    49. // send it to the computer as ASCII digits
    50. Serial.println(average);
    51. delay(1); // delay in between reads for stability
    52. }

    [Get Code]
    更多

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