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:

    • Initialize hardware (pins, sensors, displays)

    • Configure communication interfaces (Serial, I2C, SPI)

    • Set initial values for variables

    • Perform one-time initialization tasks

  • Example uses:

    cpp
    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() completes

  • Contains the main program logic that repeats indefinitely

  • Primary purposes:

    • Read sensors and inputs

    • Process data

    • Control outputs

    • Implement state machines

  • Example uses:

    cpp
    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

Characteristicsetup()loop()
ExecutionRuns once at startupRuns repeatedly forever
TimingFirst function calledCalled after setup()
Typical contentsInitialization codeMain program logic
Blocking allowed?Yes (during setup)Avoid long blocks

Best Practices

  • Keep setup() clean and focused on initialization

  • Make 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 it

  • Remember 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.

评论

此博客中的热门博文

How To Connect Stm32 To PC?

What are the common HDL languages used in FPGA design?

How do you set up ADC (Analog-to-Digital Converter) in STM32?