# 必备函数

## `setup()`

### 函数原型

```cpp
void setup();
```

### 作用

Arduino通电或复位后，即会开始执行 `setup()` 函数中的程序，该函数**只会执行一次**。

## `loop()`

### 函数原型

```cpp
void loop();
```

### 作用

在setup() 函数中的程序执行完后，Arduino会接着会**无限循环** `loop()` 函数。

## `main()` 函数呢？

我们知道，不管是C语言还是C++，程序的入口都是 `main()` 函数，那么为什么 Arduino 程序没有 `main()` 函数呢？

实际上，`main()` 函数并没有消失，它依然是 Arduino 程序的入口，只是 Arduino 设计人员将它移到了核心库里，让我们翻看一下 Arduino 核心库的 `main.cpp` 文件，它在 `Arduino安装目录/hardware/arduino/avr/cores/arduino` 里

```cpp
// main.cpp

#include <Arduino.h>

int atexit(void (* /*func*/ )()) { return 0; }

void initVariant() __attribute__((weak));
void initVariant() { }

void setupUSB() __attribute__((weak));
void setupUSB() { }

int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}
```

{% hint style="info" %}
一个程序不能有两个 `main()` 函数，Arduino 核心库已经定义了 `main()` 函数，因此我们的程序里不能包含 `main()` 函数。
{% endhint %}

## 示例

这个例子可以使 LED 闪烁

将 LED 的正极接电阻，再接 3 号引脚，负极接 GND 引脚

```cpp
/*
 * Author:  Skyone
 * Date:    2020/02/28
 * Website: https://www.skyone.host
 */

#define LED 3

void setup() {
    // Put your setup code here, to run once.
    // 将你用于初始化的代码放在这里，这些代码只会执行一次。

    pinMode(LED, OUTPUT);   // 将 `LED` 引脚初始化为输出模式
}

void loop() {
    // Put your main code here, to run repeatedly.
    // 将你的业务函数放在这里，这些代码会一直循环的运行。

    digitalWrite(LED, HIGH);    // 将 `LED` 引脚设为 高电平
    sleep(1000);                // 停止 1 秒
    digitalWrite(LED, LOW);     // 将 `LED` 引脚设为 低电平
    sleep(1000);                // 停止 1 秒
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://arduino.doc.skyone.host/core/base.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
