Section outline

  • Making Your Code Smarter and Cleaner

    As your Arduino programs get more complex, you’ll want a cleaner, smarter way to repeat tasks and organize your code. That’s where loops and functions come in.

    • 🔁 Loops – Repeating Tasks Efficiently

      Loops help you repeat a set of instructions without writing them over and over again. Arduino already uses one loop automatically — the loop() function! But there are other types of loops:

      • for loop: Repeat a block a specific number of times.
      • while loop: Keep repeating as long as a condition is true.
      • do...while loop: Like while, but runs at least once before checking.
      Example: Blink an LED 5 times using a for loop
      void setup() {
        pinMode(13, OUTPUT);
        for (int i = 0; i < 5; i++) {
          digitalWrite(13, HIGH);
          delay(500);
          digitalWrite(13, LOW);
          delay(500);
        }
      }
      
      void loop() {
        // Empty because blinking was handled in setup()
      }
    • 🧩 Functions – Reuse Your Code

      Functions help you write cleaner code by grouping repeated tasks. Instead of writing the same logic again and again, you just “call” the function.

      Example: Turning an LED ON and OFF using a function
      void blinkLED(int pin, int delayTime) {
        digitalWrite(pin, HIGH);
        delay(delayTime);
        digitalWrite(pin, LOW);
        delay(delayTime);
      }
      
      void setup() {
        pinMode(9, OUTPUT);
      }
      
      void loop() {
        blinkLED(9, 1000);
      }
    • 🎯 Benefits of Using Loops and Functions

      • Write less code, do more!
      • Make your programs easier to read and fix.
      • Organize your project like a pro.

      🛠 Tip

      Always test your function with different inputs. Try changing blinkLED(9, 1000) to blinkLED(9, 300) to see what happens.

      Now that you know how to loop and reuse code, you’re ready to handle more complex behaviors. In the next section, we’ll explore how to store and manage more data using arrays.