📅  最后修改于: 2023-12-03 14:59:31.859000             🧑  作者: Mango
The "Blink" program is a simple beginner's project for programming an Arduino board using C++ language. It demonstrates the basic functionality of turning an LED on and off at regular intervals. This tutorial will guide you through the steps to program the Arduino board to make an LED blink.
To follow along with this tutorial, you will need the following:
Before we begin writing the code, let's first set up the hardware connections. Connect the components as shown in the circuit diagram below:
+------+
| |
Digital | 13 |----|220-ohm Resistor|----- LED Anode (Long Leg)
Pin | |
+------+
| |
GND GND
Here is the C++ code to implement the Blink program:
// Pin 13 has an LED connected on Arduino boards
int ledPin = 13;
// Setup function runs once at the beginning
void setup() {
// Set pin 13 as output
pinMode(ledPin, OUTPUT);
}
// Loop function runs repeatedly after setup
void loop() {
// Turn on the LED
digitalWrite(ledPin, HIGH);
// Wait for 1000 milliseconds (1 second)
delay(1000);
// Turn off the LED
digitalWrite(ledPin, LOW);
// Wait for another 1000 milliseconds (1 second)
delay(1000);
}
Let's go through the code step by step:
int ledPin = 13;
: This line declares a variable ledPin
and assigns the value 13
to it. This variable will represent the digital pin connected to the LED.
void setup() { ... }
: The setup()
function is a special function in Arduino, which runs once when the board powers up. In this function, we set the ledPin
as an output pin using the pinMode()
function.
void loop() { ... }
: The loop()
function is another special function that runs repeatedly after the setup()
function. Here, we define the logic for blinking the LED.
digitalWrite(ledPin, HIGH);
: This line turns on the LED by setting the ledPin
to HIGH
(5V).
delay(1000);
: This line pauses the program for 1000 milliseconds (1 second).
digitalWrite(ledPin, LOW);
: This line turns off the LED by setting the ledPin
to LOW
(0V).
delay(1000);
: This line pauses the program for another 1000 milliseconds.
The loop()
function will continue to run indefinitely, causing the LED to blink on and off every 1 second.
In this tutorial, we learned how to write a simple C++ program to make an LED blink using an Arduino board. By understanding this basic example, you can explore more advanced projects and functionalities with Arduino and C++ programming.
Happy tinkering!