一、Blink示例
点击“文件”——“示例”——“Basics”——“Blink”打开Blink示例程序。Blink有眨眼、闪亮之意,程序实现的功能也与之类似,可以让板子上的L灯以1秒为间隔点亮熄灭。
二、程序讲解
/*
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.
https://www.arduino.cc/en/Tutorial/BuiltInExamples/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
}
开头一长串注释是在解释这个代码的作用。
函数“setup”只在上电或者按下复位键使执行一次,函数体里的内容是将“LED_BUILTIN”的模式设置为输出,起到初始化的作用。在新版IDE中,每一个函数、串口都可以右键选择“快速查看”,即可看到函数或串口的定义:
下一个函数“loop”,注释中写道它会在程序运行过程中不断重复运行,相当于一个循环。在此函数中,程序一共做了四件事:
digitalWrite(LED_BUILTIN, HIGH);
调用digitalWrite,在LED_BUILTIN写入HIGH,输出高电平,即点亮LED。
delay(1000);
调用delay函数,让程序等待1秒再进行下一步操作。
digitalWrite(LED_BUILTIN, LOW);
继续调用digitalWrite,在LED_BUILTIN写入LOW,输出低电平,熄灭LED。
delay(1000);
再等待1秒。
通过这个loop函数,执行一次可以让LED亮一次、等1秒、灭一次、再等一秒。如此循环,即可实现LED一亮一灭的效果,看起来就像人在眨眼。
三、验证烧录
IDE上方这两个按钮,左边是验证,IDE会检测程序是否有错误。右边是上传,将无误的程序烧录到板子中。
点击上传,输出出现以上字样则代表烧录成功,此时可以看到板子上的LED在按照我们预想的亮一秒灭一秒。