Blink 实验,测试Arduino IDE - 02

简介

安装好 Arduino IDE 后,我们接下来使用 IDE 自带的 Blink 例子测试 IDE 与 Arduino 板的通信是否正常。

Blink 是 IDE 自带的源代码示例之一,源代码通过 IDE 的编译并上传到 Arduino 板后,会控制板载的 LED 灯闪烁,一秒亮一秒熄灭。

物料

  • Arduino Uno
  • USB 数据线

步骤

在电脑不和Arduino 板连线的情况下,打开 Arduino IDE, 选择Tools (工具 ) → Port(端口) 。

此时只有一个串口 /dev/cu.Bluetooth-Incoming-Port 。

然后用USB 数据线把 Arduino 板和电脑连起来,再次打开 Arduino IDE, 选择Tools (工具 ) → Port(端口) 。将会看到新增了其他端口,这也就是电脑和Arduino 板的通信端口。在本人的电脑上,与Arduino 的通信端口是 /dev/cu.wchusberial1410 ,在你的电脑上可能是其他端口号。

打开 File(文件)→Examples(例子)→01.Basics→Blink

打开后 IDE 就会出现如下代码:

代码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Blink

Turns an LED on for one second, then off for one second, repeatedly.

Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
the correct LED pin independent of which board is used.
If you want to know what pin the on-board LED is connected to on your Arduino
model, check the Technical Specs of your board at:
<https://www.arduino.cc/en/Main/Products>

modified 8 May 2014
by Scott Fitzgerald
modified 2 Sep 2016
by Arturo Guadalupi
modified 8 Sep 2016
by Colby Newman

This example code is in the public domain.

<http://www.arduino.cc/en/Tutorial/Blink>
*/

// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

注释

代码使用 “/* …… /” 和 “ // ” 两种符号进行注释。所谓的注释是书写给人阅读,以便他人或自己日后能清楚代码是干什么的。IDE 不会对注释的内容进行任何处理。其实 “/……*/” 是块注释,能跨行注释内容;“ // ” 是单行注释,只能注释一行的内容。

函数

Arduino 的程序结构主要由 setup() 和 loop() 两个函数构成。那么,什么是函数呢?

函数是一种最基本的任务模块,它由一组可以一起执行一个任务的语句组成。

1
2
3
4
返回类型 函数名(参数1,参数2,参数3,...){
语句块;
返回值;
}

返回类型 —- 函数执行完毕后返回的数值类型,类型有 整形,浮点型,字符串等。若返回类型为void,函数不需要返回值;

函数名 — 函数的名字,通过函数名可以调用函数;

参数 — 调用函数时,传递给函数的值;

返回值 — 函数执行完毕后,把结果返回给调用者。如果没有结果需要返回,可以忽略;

以上是函数的语法,在此实验中,只需要了解即可,不需要深究。

setup() 函数

源代码通过 IDE 编译并上传到板后重设板子或者开机通电后会执行一次 setup() 函数,通过它可以初始化程序的引脚、变量等。

1
2
3
4
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}

pinMode(LED_BUILTIN, OUTPUT);

把 LED_BUILTIN 引脚定义为输出模式,在 UNO,MEGA 和 ZERO 板中,LED_BUILTIN 引脚为 13 。

loop() 函数

Arduino 板上电后,setup() 函数运行结束,初始化完毕。就会进入 loop() 函数。

loop() 函数顾名思义是循环,它会无限次循环执行其函数体里面的语句。

编译,上传

效果如下:

如何在一台机器上管理多个 Github 账号 Arduino IDE 下载和安装 - 01

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×