这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录前一修订版 | |||
learing:examples:array [2017/10/05 03:41] – 弘毅 | learing:examples:array [2023/06/07 04:23] (当前版本) – 外部编辑 127.0.0.1 | ||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== Arrays(数组) ====== | ||
+ | |||
+ | |||
+ | |||
+ | 这些loop循环中的变量演示了数组的用法。数组是有多部分构成的变量。如果把变量看作是存储数值的杯子的话,数组就是托盘。就像一系列连起来的杯子一样,所有的杯子都能存储同样的最大值。 | ||
+ | |||
+ | for循环的例子演示了点亮一系列LED灯的方法,但是有局限性,就是引脚号必须是连续的,LED也只能依次点亮。 | ||
+ | |||
+ | |||
+ | 这个例子教你打开一系列不连续的引脚,你可以把引脚数字放入数组,用for遍历数组。 | ||
+ | |||
+ | |||
+ | 这个例子使用6个用220欧姆电阻连在2-7号引脚的LED,就和for循环中的一样。然而,这里LED的顺序是由数组里的顺序决定的,而不是物理顺序。 | ||
+ | |||
+ | |||
+ | 把引脚放进数组的方法是很方便的。你不需要按顺序连接引脚,而是可以自由的分配。 | ||
+ | |||
+ | |||
+ | ======LED规律闪烁====== | ||
+ | |||
+ | <WRAP left round info 100%> | ||
+ | 这个例程创建了LED引脚数组,根据数组的规定来使多个LED规律闪烁。 | ||
+ | </ | ||
+ | |||
+ | ==== 硬件 ==== | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | * [[ocrobot: | ||
+ | |||
+ | ==== 搭建电路 ==== | ||
+ | |||
+ | - ALPHA 11 LED模块插入并行扩展版1号槽位。 | ||
+ | - ALPHA MEGA328-U模块插入并行扩展板2号槽位。 | ||
+ | - USB线连接计算机与ALPHA MEGA328-U。 | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | ==== 代码 ==== | ||
+ | |||
+ | |||
+ | <code cpp>/* | ||
+ | Arrays,创建LED引脚数组,根据引脚位置在数组中的不同,来使多个LED规律闪烁 | ||
+ | */ | ||
+ | |||
+ | int timer = 100; // 数值越大,计时器越慢 | ||
+ | int ledPins[] = { | ||
+ | 2, 7, 4, 6, 5, 3 ,8 ,11 ,12 ,9 ,10 | ||
+ | }; // 连接LED的引脚号的数组 | ||
+ | int pinCount = 10; // 引脚个数 | ||
+ | void setup() { | ||
+ | // 数组从0到pinCount - 1 | ||
+ | // 使用for循环来初始化引脚为输出 | ||
+ | for (int thisPin = 0; thisPin < pinCount; thisPin++) { | ||
+ | pinMode(ledPins[thisPin], | ||
+ | } | ||
+ | } | ||
+ | |||
+ | void loop() { | ||
+ | // 最小引脚号到最大引脚号循环 | ||
+ | for (int thisPin = 0; thisPin < pinCount; thisPin++) { | ||
+ | // 打开: | ||
+ | digitalWrite(ledPins[thisPin], | ||
+ | delay(timer); | ||
+ | // 关闭: | ||
+ | digitalWrite(ledPins[thisPin], | ||
+ | |||
+ | } | ||
+ | |||
+ | // 最大引脚号到最小引脚号循环: | ||
+ | for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) { | ||
+ | // 打开: | ||
+ | digitalWrite(ledPins[thisPin], | ||
+ | delay(timer); | ||
+ | // 关闭: | ||
+ | digitalWrite(ledPins[thisPin], | ||
+ | } | ||
+ | }</ | ||
+ | |||