What is the difference between setup() and loop() functions?
These functions are fundamental to Arduino programming (and similar embedded frameworks), serving distinct purposes:
setup()
Function
Runs once when the microcontroller starts or after a reset
Primary purposes:
Example uses:
void setup() { pinMode(LED_PIN, OUTPUT); // Set pin as output Serial.begin(9600); // Initialize serial communication display.begin(); // Initialize OLED display }
loop()
Function
Runs continuously after
setup()
completesContains the main program logic that repeats indefinitely
Primary purposes:
Read sensors and inputs
Process data
Control outputs
Implement state machines
Example uses:
void loop() { int sensorValue = analogRead(A0); // Read sensor Serial.println(sensorValue); // Send data to PC digitalWrite(LED_PIN, HIGH); // Turn on LED delay(1000); // Wait 1 second digitalWrite(LED_PIN, LOW); // Turn off LED delay(1000); }
Key Differences
Characteristic | setup() | loop() |
---|---|---|
Execution | Runs once at startup | Runs repeatedly forever |
Timing | First function called | Called after setup() |
Typical contents | Initialization code | Main program logic |
Blocking allowed? | Yes (during setup) | Avoid long blocks |
Best Practices
Keep
setup()
clean and focused on initializationMake
loop()
as efficient as possible (avoid long delays when possible)For complex programs, call separate functions from
loop()
rather than putting all code directly in itRemember that
loop()
must never exit - it should run continuously
This structure (setup()
+ loop()
) provides a simple framework for embedded programming while abstracting away low-level details of the microcontroller's operation.
评论
发表评论