The main function of an Arduino program (often referred to as a "sketch") is the `setup()` and `loop()` functions. Here’s a detailed breakdown of their roles:
### 1. `setup()` Function
- **Purpose**: The `setup()` function is called once when the program starts. It's used to initialize variables, pin modes, start using libraries, and perform any setup tasks that need to be done before the main loop runs.
- **Usage**: You typically set the pin modes (input/output) and initialize communication protocols (like serial communication) in this function.
- **Example**:
```cpp
void setup() {
Serial.begin(9600); // Starts the serial communication at 9600 baud rate
pinMode(LED_BUILTIN, OUTPUT); // Sets the built-in LED pin as an output
}
```
### 2. `loop()` Function
- **Purpose**: The `loop()` function runs continuously after the `setup()` function has completed. This is where you put the main code that you want to run repeatedly.
- **Usage**: You might read sensor data, update outputs, check for conditions, or perform any repetitive tasks in this function.
- **Example**:
```cpp
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // Turns the LED on
delay(1000); // Wait for a second
digitalWrite(LED_BUILTIN, LOW); // Turns the LED off
delay(1000); // Wait for a second
}
```
### Full Sketch Example
Here’s how a complete Arduino sketch might look with both functions:
```cpp
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(LED_BUILTIN, OUTPUT); // Set the LED pin as output
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
delay(1000); // Wait for a second
digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
delay(1000); // Wait for a second
}
```
### Summary
- **`setup()`** is for initial configurations that run once.
- **`loop()`** runs indefinitely, allowing for continuous execution of your program's logic.
### Additional Notes
- **Other Functions**: Besides `setup()` and `loop()`, you can create other functions to organize your code better. For example, you might have functions for handling specific tasks (like reading a sensor or controlling a motor).
- **Interrupts**: You can also handle events using interrupts, which allow you to respond to events while the main loop is running.
- **Libraries**: Arduino has a vast ecosystem of libraries that can extend functionality, making it easier to work with different sensors, displays, and communication protocols.
By understanding these functions and how they interact, you can start programming your Arduino effectively!