用户工具

站点工具


learing:examples:forloop

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录前一修订版
后一修订版
前一修订版
zh:learing:examples:forloop [2016/03/17 07:47] 董凯萍learing:examples:forloop [2023/06/07 04:23] (当前版本) – 外部编辑 127.0.0.1
行 1: 行 1:
 +====== For Loop Iteration (aka The Knight Rider)(循环) ======
  
 +
 +你经常会遇到要遍历一系列引脚并且使用每一个引脚。例如,这个例子通过使用for()循环来使连接在arduino上的2-7号数字引脚的6个LED闪烁, 使用digitalWrite() 和delay() 使这些LED连续的亮灭。
 +
 +
 +我们也叫它霹雳游侠,是为了纪念80年代系列电视剧霹雳游侠David Hasselhoff 的智能汽车 KITT ,这部车装了很多型号的LED能展示酷炫的效果。尤其是,它有一个来回滚动字幕的显示屏,就是在KITT 和 KARR对战里看到的那样。这个例子重现了KITT的效果。
 +
 +======多个LED闪烁======
 +
 +<WRAP left round info 100%>
 +这个例程显示了多个LED闪烁的效果。
 +</WRAP>
 +
 +
 +
 +==== 硬件 ====
 +  * [[ocrobot:alpha:parallelexpansion:index|ALPHA 并行扩展板]]
 +  * [[ocrobot:alpha:mega328-u:main|ALPHA MEGA328-U]]
 +  * [[ocrobot:alpha:11led:index|ALPHA 11 LED模块]]
 +
 +==== 搭建电路 ====
 +
 +  - ALPHA 11 LED模块插入并行扩展版1号槽位。
 +  - ALPHA MEGA328-U模块插入并行扩展板2号槽位。
 +  - USB线连接计算机与ALPHA MEGA328-U。
 +==== 代码 ====
 +
 +
 +下面的代码使用for循环来分配2-12号引脚给10个LED作为输出使用。
 +
 +
 +在主循环中,使用了两个for()循环,一个个分配led从2-12号。12号分配好以后,程序继续反过来分配每一个LED。
 +
 +<code cpp>/*
 +  For Loop Iteration
 +*/
 +
 +int timer = 100;           // 数值越大 计时器越慢
 +void setup() {
 +  // 初始化引脚为输出:
 +  for (int thisPin = 2; thisPin < 13; thisPin++) {
 +    pinMode(thisPin, OUTPUT);
 +  }
 +}
 +
 +void loop() {
 +  // 从最小号的引脚循环到最大号的引脚
 +  for (int thisPin = 2; thisPin < 13; thisPin++) {
 +    // 点亮LED:
 +    digitalWrite(thisPin, HIGH);
 +    delay(timer);
 +    // 熄灭LED:
 +    digitalWrite(thisPin, LOW);
 +  }
 +
 +  // 从从最大号的引脚循环到最小号的引脚:
 +  for (int thisPin = 13; thisPin >= 2; thisPin--) {
 +    // 点亮LED:
 +    digitalWrite(thisPin, HIGH);
 +    delay(timer);
 +    // 熄灭LED:
 +    digitalWrite(thisPin, LOW);
 +  }
 +}</code>