Arduino内置教程-模拟-模拟写入Mega

模拟写入Mega

这个例子利用板上的数字引脚的PWM数目优势,使在Arduino或者Genuino Mega开发板上的12个LED灯一个接一个变暗和变亮。

硬件要求

  • Arduino 或者 Genuino Mega开发板
  • 12 Red LED灯
  • 12 220 ohm 电阻
  • 连接线
  • 面包板

电路

请输入图片描述

把12个LED灯的长脚(正极或者阳极)通过220 ohm限流电阻连接到数字引脚pin2-13。连接短腿(负极或阴极)到地。

原理图

请输入图片描述

样例代码

  • 在以下程序的setup()函数里,for()循环用来分配Mega板上的数字引脚pin2-13的输出。

  • 然后,在下面的loop()函数里,用上for()循环三重嵌套。

  • 三个循环的第一个循环

for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++)
  • LED灯从最低位到最高一个接一个地移动。在这个循环允许从一个引脚移到下一个前,两件事必须完成。第一件是你使特定的LED灯通过这些代码变亮:
for (int brightness = 0; brightness < 255; brightness++) {
analogWrite(thisPin, brightness);
delay(2);
}
  • 伴随上面的每次循环,变量brightness增加到一点,然后这个值写入到主循环里被选中当前引脚。当引脚达到PWM值(255),进入到下面的循环:
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(thisPin, brightness);
delay(2);
}
  • 这个循环使brightness变量每次减去一点,使LED灯逐渐变暗直至0。一旦达到0,就会进入主循环的for循环,并且程序会移动到下一个LED灯,重复上面的步骤。
/*
  Mega analogWrite() test

  This sketch fades LEDs up and down one at a time on digital pins 2 through 13.
  This sketch was written for the Arduino Mega, and will not work on previous boards.

  The circuit:
  * LEDs attached from pins 2 through 13 to ground.

  created 8 Feb 2009
  by Tom Igoe

  This example code is in the public domain.

 */
// These constants won't change.  They're used to give names
// to the pins used:
const int lowestPin = 2;
const int highestPin = 13;


void setup() {
  // set pins 2 through 13 as outputs:
  for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  // iterate over the pins:
  for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
    // fade the LED on thisPin from off to brightest:
    for (int brightness = 0; brightness < 255; brightness++) {
      analogWrite(thisPin, brightness);
      delay(2);
    }
    // fade the LED on thisPin from brithstest to off:
    for (int brightness = 255; brightness >= 0; brightness--) {
      analogWrite(thisPin, brightness);
      delay(2);
    }
    // pause between LEDs:
    delay(100);
  }
}

[Get Code]

更多

  • for()
  • analogWrite()
  • delay()
  • AnalogInOutSerial - 读取一个模拟输入引脚,按比例划分读数,然后用这个数据来熄灭或者点亮一个LED灯
  • AnalogInput - 用电位计来控制LED灯闪烁
  • Calibration - 定义期望中的模拟传感值的最大值和最小值
  • Fading - 用模拟输出(PWM引脚)来使LED灯变亮或者变暗
  • Smoothing - 使多个模拟输入引脚的读取值变得平滑

标签: arduino内置教程, arduino模拟写入mega