ARDUINO IDE
setup()
This function is called when the program begins. Use it to initialize variables, pin modes, start using libraries, etc. setup() runs only once each time the Arduino board is powered on or reset.
void setup()
Common things you do in setup():
- Set pin modes (INPUT, OUTPUT, INPUT_PULLUP)
- Initialize serial communication
- Set up libraries (sensors, displays, etc.)
- Set initial states (turn LEDs off, etc.)
- Configure timers or interrupts
loop()
After the program in setup() is executed, the program in loop() begins to execute. The program in loop() runs repeatedly.
void loop()
This runs over and over forever after setup() finishes.
Key insight: If you want something to happen once, put it in setup(). If you want it to happen continuously, put it in loop().
Why "void"?
void means these functions don't return any value. They just *do* things.
In Arduino programming, the keyword void is used in front of function names such as setup() and loop().
The term void indicates that these functions do not return any value when they finish executing.
Unlike functions that calculate a value and send it back to the program, void functions simply perform a set of instructions or actions.
For example, a function that turns on a light or prints a message can be declared as void because it doesnβt need to give anything back to the program. It just does its job. Similarly, functions that prepare the board or continuously run a program are often void since they only carry out instructions.
Using void makes it clear that the function is for performing tasks, not for producing a value to use somewhere else.
For example, setup() initializes pins, starts serial communication, or sets initial values, while loop() repeatedly runs the main program logic.
Neither function needs to send a result back, so they are declared with void.
In programming, not all functions are void. Some functions return a value that can be used elsewhere in the program.
The type of value a function returns is specified by keywords like int, float, char, or bool.
Common return types:
1. int
Stands for integer (whole numbers). Functions that return int will give back numbers like 0, 5, or -12.
2. float
Represents decimal numbers. Functions that return float can give back values like 3.14 or -0.5.
3. char
Represents a single character, such as 'A', 'b', or '7'.
4. bool
Represents a boolean value: true or false. Useful for checking conditions.
Using the correct return type is important because it tells the computer what kind of value to expect from the function.
Knowledge window:
- The contents inside "/* */" and after "//" are comments to help you understand and manage code, the comments will not affect the normal operation of the program;
- When writing programs, we need to use "{}" to wrap a set of codes;
- After each line of code, use ";" as an end symbol to tell the Arduino editor that this line of code instruction is over.
XIAO Pins
Seeed Studio XIAO has 11 digital pins, we can set these pins to perform the function of inputting or outputting digital signals.
In Arduino, you can use functions to set the status and function of pins. Here are the basic steps to set pins through functions:
- First, determine the pin number of the pin you want to control.
- In the Arduino code, use the pinMode() function to set the function of the pin, such as input or output.
What is pinMode()?
It tells the Arduino: "Hey, I'm going to use this pin as an INPUT or an OUTPUT."
Think of Arduino pins like doors in a building:
- OUTPUT = door that only lets things OUT (Arduino sends signals out)
- INPUT = door that only lets things IN (Arduino receives signals in)
The Syntax:
pinMode(pin_number, mode);
Example:
void setup() {
pinMode(13, OUTPUT); // Pin 13 will SEND signals (like to an LED)
pinMode(2, INPUT); // Pin 2 will RECEIVE signals (like from a button)
}
The Three Modes:
1. OUTPUT
The OUTPUT mode is used when an output device is connected to the Arduino. An output device is any component that receives signals from the Arduino to perform an action.
When a pin is set as OUTPUT, it is configured to send electrical signals to the connected device. This allows the Arduino to control components such as LEDs, buzzers, relays, or motor drivers.
The OUTPUT mode is used when you want the Arduino to send signals or control something.
Setting a pin as OUTPUT tells the board that this pin will provide power to an external device.
For example, when a pin is in OUTPUT mode, it can make an LED light up, make a buzzer sound, or control other devices that need a signal from the Arduino.
In simple terms, if a device needs to receive signals from the Arduino to work, the connected pin must be set to OUTPUT.
pinMode(13, OUTPUT); // Pin 13 is set to OUTPUT mode
2. INPUT
The INPUT mode is used when an input device is connected to the Arduino. An input device is any component that sends information to the Arduino so it can read or detect something.
When a pin is set as INPUT, it is configured to receive electrical signals from the connected device. This allows the Arduino to read the state of components such as buttons, switches, or sensors.
In simple terms, if a device sends information to the Arduino, the connected pin must be set to INPUT.
pinMode(2, INPUT); // Pin 2 is configured to read signals from an input device
3. INPUT_PULLUP
The INPUT_PULLUP mode is a special type of input mode. It is used when you connect an input device, like a button, to the Arduino, and you want to use the board's internal pull-up resistor.
Setting a pin as INPUT_PULLUP automatically connects a small resistor inside the Arduino. This helps the pin read a stable signal from devices like buttons without needing an external resistor.
In simple terms, if you want to read a button or switch and donβt want to add extra components, you can set the pin to INPUT_PULLUP so the Arduino handles the electrical setup for you.
pinMode(2, INPUT_PULLUP); // Pin 2 is set as an input with internal pull-up resistor
Important Rules:
- Always set pinMode in setup() - do it once at the beginning
- You must set pinMode before using a pin - Arduino needs to know your plan
- Each pin can only be one mode at a time - can't be both INPUT and OUTPUT
Simple Example:
void setup() {
pinMode(13, OUTPUT); // Pin 13 controls an LED
}
void loop() {
// Now we can use pin 13 to turn LED on/off
// (we'll learn digitalWrite() next!)
}
digitalWrite()
This is how you actually turn things ON or OFF on OUTPUT pins.
The Syntax:
digitalWrite(pin_number, value);
Value can be:
- HIGH = Turn it ON (send 5V)
- LOW = Turn it OFF (send 0V)
Examples:
digitalWrite(13, HIGH); // Turn pin 13 ON (5 volts)
digitalWrite(13, LOW); // Turn pin 13 OFF (0 volts)
Real Working Code:
void setup() {
pinMode(13, OUTPUT); // First: tell Arduino pin 13 is an output
}
void loop() {
digitalWrite(13, HIGH); // Turn LED ON
digitalWrite(13, LOW); // Turn LED OFF immediately after
// This happens SO FAST you won't see it blink!
}
Problem: This blinks too fast to see! The Arduino runs millions of instructions per second.
Solution: We need to add waiting time between ON and OFF. That's where delay() comes in (next topic).
Key Points:
- Only works on OUTPUT pins - you must set pinMode(pin, OUTPUT) first
- HIGH = ON = 5V (or 3.3V on some boards)
- LOW = OFF = 0V
- You can use numbers too: digitalWrite(13, 1) same as HIGH, digitalWrite(13, 0) same as LOW
- But HIGH/LOW is clearer - use those!
Think of it like a light switch:
- digitalWrite(13, HIGH) = flip switch UP
- digitalWrite(13, LOW) = flip switch DOWN
delay()
This makes Arduino wait (pause) for a certain amount of time.
The Syntax:
delay(milliseconds);
Time is in milliseconds:
- 1000 milliseconds = 1 second
- 500 milliseconds = 0.5 seconds (half second)
- 100 milliseconds = 0.1 seconds
Examples:
delay(1000); // Wait 1 second
delay(500); // Wait half a second
delay(100); // Wait 0.1 seconds
delay(5000); // Wait 5 seconds
Now Let's Make an LED Blink!
void setup() {
pinMode(13, OUTPUT); // Pin 13 is an output
}
void loop() {
digitalWrite(13, HIGH); // Turn LED ON
delay(1000); // Wait 1 second (LED stays ON)
digitalWrite(13, LOW); // Turn LED OFF
delay(1000); // Wait 1 second (LED stays OFF)
// loop() repeats, so it blinks forever!
}
What happens:
- LED turns ON
- Waits 1 second (ON the whole time)
- LED turns OFF
- Waits 1 second (OFF the whole time)
- Goes back to step 1, repeats forever
Experimenting with Timing:
// Fast blink
digitalWrite(13, HIGH);
delay(100); // ON for 0.1 sec
digitalWrite(13, LOW);
delay(100); // OFF for 0.1 sec
// Slow blink
digitalWrite(13, HIGH);
delay(2000); // ON for 2 sec
digitalWrite(13, LOW);
delay(2000); // OFF for 2 sec
// SOS pattern!
digitalWrite(13, HIGH);
delay(200); // Short blink
digitalWrite(13, LOW);
delay(200);
Important:
- During delay(), Arduino does NOTHING - it's frozen, just waiting
- Can't read buttons or sensors while delay is running
- We'll learn better ways later (millis), but delay is perfect for learning!
digitalRead()
Now you know how to control things (OUTPUT). Let's learn how to sense things (INPUT)!
digitalRead() lets Arduino read the state of a pin - is it HIGH or LOW?
The Syntax:
digitalRead(pin_number);
Returns:
- HIGH (or 1) = pin is receiving 5V
- LOW (or 0) = pin is receiving 0V
Common Use: Reading a Button
When you press a button, it connects a pin to power (HIGH) or ground (LOW).
void setup() {
pinMode(2, INPUT); // Pin 2 will read the button
}
void loop() {
int buttonState = digitalRead(2); // Read pin 2
// buttonState now contains either HIGH or LOW
}
Real Example: Button Controls LED
void setup() {
pinMode(2, INPUT); // Button connected to pin 2
pinMode(13, OUTPUT); // LED connected to pin 13
}
void loop() {
int buttonState = digitalRead(2); // Read the button
if (buttonState == HIGH) {
digitalWrite(13, HIGH); // Button pressed β LED ON
}
else {
digitalWrite(13, LOW); // Button not pressed β LED OFF
}
}
What happens:
- When button is pressed β pin 2 reads HIGH β LED turns ON
- When button is released β pin 2 reads LOW β LED turns OFF
Key Points:
- Only works on INPUT pins - must set pinMode(pin, INPUT) first
- Returns HIGH or LOW - you can store it in a variable
- Digital means only 2 states - either HIGH or LOW, nothing in between
- Reads the state right now - it's instant
Storage Tip:
You can store the result:
int buttonState = digitalRead(2); // Store it
Or use it directly:
if (digitalRead(2) == HIGH)
{
// Use it immediately
// do something
}
analogRead()
We've been working with digital - only two states (HIGH/LOW, ON/OFF).
Now let's read analog - a range of values from 0 to 1023.
What's Analog?
Digital: Light switch - either ON or OFF
Analog: Dimmer switch - can be at any brightness level between fully off and fully on
Analog signals, can have many values between fully off and fully on, like a dimmer switch for a light. This means the Arduino can read a range of values, not just two.
When you use analogRead(), the Arduino reads this range of values and gives a number between 0 (fully off) and 1023 (fully on).
This allows you to measure things like sensor levels, brightness, or anything that changes gradually.
Imagine your room is a little too bright while youβre reading your favorite book. You donβt want to turn the light completely off β you just want it gentle and cozy.
So, you reach for a magical dimmer switch that lets you adjust the brightness anywhere between fully bright and completely dark. You slide it until the light feels just right for your eyes.
analogRead() works in a similar way. Instead of just saying ON or OFF like a normal light switch, it lets the Arduino βsenseβ the exact level of light. It can read small changes and give a number from 0 (dark) to 1023 (bright), so your program can respond to any light level β just like adjusting your magical dimmer.
The Syntax:
analogRead(pin_number);
Returns: A number from 0 to 1023
- 0 = 0 volts
- 1023 = 5 volts
- 512 = 2.5 volts (middle)
Important: Special Pins Only!
You can only use analogRead() on analog pins: A0, A1, A2, A3, A4, A5
(On Arduino Uno, these are labeled with an "A")
Common Analog Sensors:
- Potentiometer (knob) - turn it to get different values
- Light sensor (LDR) - brighter = higher value
- Temperature sensor - hotter = different value
- Joystick - position = different value
Example: Reading a Potentiometer
void setup() {
pinMode(A0, INPUT); // Optional - analog pins default to INPUT
}
void loop() {
int sensorValue = analogRead(A0); // Read analog pin A0
// sensorValue now contains a number from 0 to 1023
// 0 = knob turned fully left
// 512 = knob in the middle
// 1023 = knob turned fully right
}
Digital vs Analog:
// DIGITAL - only 2 possible values
int buttonState = digitalRead(2); // Returns HIGH or LOW
// ANALOG - 1024 possible values!
int knobValue = analogRead(A0); // Returns 0 to 1023
Key Points:
- Only works on A0-A5 pins (analog pins)
- Returns 0 to 1023 (not just HIGH/LOW)
- No pinMode needed (analog pins are INPUT by default, but you can set it anyway)
- Great for sensors that have varying levels, not just on/off
Serial Monitor
This is your window into Arduino's brain - it lets you see values, debug code, and understand what's happening!
What Is It?
The Serial Monitor is a tool in the Arduino IDE that displays messages from your Arduino on your computer screen.
Think of it like Arduino sending you text messages!
The Two Commands:
1. Serial.begin(speed) - Start communication
Put this in setup() once:
void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud
}
The number 9600 is called the baud rate. It tells the Arduino how fast to send data to your computer over the serial connection. Specifically, it means the Arduino sends 9600 bits per second. A bit is the smallest piece of data β either a 0 or 1 β so 9600 bits per second is like sending 9600 tiny pieces of information every second.
For beginners, 9600 is a good speed because it is slow enough to be reliable, but fast enough to see results quickly in your programs.
9600 = speed of communication (bits per second). Always use 9600 for beginners.
2. Serial.print() and Serial.println() - Send messages
Serial.print("Hello"); // Prints text, cursor stays on same line
Serial.println("Hello"); // Prints text, then moves to next line
Difference:
- print() = no line break after
- println() = adds line break after (ln = line)
Example: See Analog Values!
void setup() {
Serial.begin(9600); // Start serial communication
pinMode(A0, INPUT);
}
void loop() {
int sensorValue = analogRead(A0); // Read the sensor
Serial.println(sensorValue); // Send the value to computer
delay(100); // Wait a bit so values don't scroll too fast
}
To see the values:
- Upload this code to Arduino
- Click the magnifying glass icon (π) in Arduino IDE
- Watch the numbers appear!
Printing Multiple Things:
int value = analogRead(A0);
Serial.print("Sensor value: "); // Text
Serial.println(value); // Number + new line
// Output: Sensor value: 512
Super Useful For:
- Debugging - see what your variables contain
- Testing sensors - see what values you're getting
- Understanding code - see which parts run and when
void loop() {
Serial.println("Loop started");
int button = digitalRead(2);
Serial.print("Button state: ");
Serial.println(button);
delay(500);
}
Key Points:
- Always Serial.begin(9600) in setup() - do this first!
- print() = no new line, println() = new line after
- Open Serial Monitor with magnifying glass icon (π) or Ctrl+Shift+M
- Match baud rate - if you use Serial.begin(9600), set Serial Monitor to 9600 too
Quick Example - Complete Debug Code:
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
Serial.println("Arduino started!");
}
void loop() {
Serial.println("LED ON");
digitalWrite(13, HIGH);
delay(1000);
Serial.println("LED OFF");
digitalWrite(13, LOW);
delay(1000);
}
Upload this and open Serial Monitor - you'll see "LED ON" and "LED OFF" messages!
analogWrite()
This lets you output in-between values, not just ON/OFF!
What It Does:
digitalWrite()= fully ON or fully OFFanalogWrite()= anywhere from 0% to 100% power
Uses:
- Dim an LED (not just full brightness or off)
- Control motor speed (not just full speed or stopped)
- Control servo position
The Syntax:
analogWrite(pin_number, value);
Value: 0 to 255
- 0 = 0% power (OFF)
- 127 = 50% power (half brightness)
- 255 = 100% power (full brightness/ON)
Important: PWM Pins Only!
You can only use analogWrite() on PWM pins (marked with ~ symbol):
On Arduino Uno: 3, 5, 6, 9, 10, 11
Example: Dimming an LED
void setup() {
pinMode(9, OUTPUT); // Pin 9 is a PWM pin
}
void loop() {
analogWrite(9, 0); // LED off
delay(500);
analogWrite(9, 64); // LED at 25% brightness
delay(500);
analogWrite(9, 128); // LED at 50% brightness
delay(500);
analogWrite(9, 255); // LED at 100% brightness (full)
delay(500);
}
Fade Effect:
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
// Fade up from 0 to 255
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(9, brightness);
delay(10);
}
// Fade down from 255 to 0
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(9, brightness);
delay(10);
}
}
Quick Comparison:
| Command | Input/Output | Pins | Values | Purpose |
|---|---|---|---|---|
digitalRead() |
Input | Any digital | HIGH/LOW | Read button/sensor |
digitalWrite() |
Output | Any digital | HIGH/LOW | Turn LED on/off |
analogRead() |
Input | A0-A5 | 0-1023 | Read sensor range |
analogWrite() |
Output | PWM pins (~) | 0-255 | Dim LED/control speed |
How It Really Works (PWM):
analogWrite() doesn't actually send different voltages - it rapidly pulses ON/OFF so fast it looks continuous!
analogWrite(9, 255)= ON 100% of the timeanalogWrite(9, 128)= ON 50%, OFF 50% (so fast you see half brightness)analogWrite(9, 64)= ON 25%, OFF 75%
This is called PWM (Pulse Width Modulation) - we can dive deeper later!
Variables
Variables are like labeled boxes where you store information to use later.
Why Use Variables?
Instead of writing the same number over and over, store it once and reuse it!
Without variables:
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
// If you want to change timing, you have to change it in multiple places!
With variables:
int delayTime = 1000;
digitalWrite(13, HIGH);
delay(delayTime);
digitalWrite(13, LOW);
delay(delayTime);
// Change timing in ONE place!
Creating a Variable:
int myNumber = 42;
Parts:
- int = type of data (integer = whole number)
- myNumber = name you choose
- = = assign/store
- 42 = the value
- ; = end of statement
Common Data Types:
1. int - Whole numbers
int age = 25;
int sensorValue = 512;
int ledPin = 13;
Range: -32,768 to 32,767
2. float - Decimal numbers
float temperature = 23.
float voltage = 3.14;
3. boolean - True or false
boolean ledState = true;
boolean buttonPressed = false;
Only two values: true or false
4. char - Single character
char letter = 'A';
char grade = 'B';
Use single quotes ' '
Using Variables:
void setup() {
Serial.begin(9600);
int sensorValue = analogRead(A0);
Serial.print("Sensor reads: ");
Serial.println(sensorValue);
}
Variable Names - Rules:
β Good names:
int ledPin = 13;
int buttonState = 0;
int delayTime = 1000;
β Bad (won't work):
int 123pin = 13; // Can't start with number
int led-pin = 13; // Can't use dashes
int my pin = 13; // Can't have spaces
Rules:
- Must start with letter or underscore
- Can contain letters, numbers, underscore
- No spaces, no special characters
- Case sensitive: ledPin β LedPin
Changing Variables:
int counter = 0; // Start at 0
counter = 5; // Now it's 5
counter = counter + 1; // Now it's 6
counter++; // Now it's 7 (shortcut for +1)
Practical Example:
int ledPin = 13;
int delayTime = 500;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(delayTime);
digitalWrite(ledPin, LOW);
delay(delayTime);
// Easy to change! Just modify delayTime at the top
}
Where to Declare Variables:
// GLOBAL - available everywhere
int ledPin = 13;
void setup() {
// LOCAL - only available inside setup()
int startupDelay = 2000;
delay(startupDelay);
}
void loop() {
// LOCAL - only available inside loop()
int sensorValue = analogRead(A0);
}
Rule of thumb: Declare at the top (global) if you need it in multiple places.
Key Points:
- Variables store information to reuse later
- Choose the right type: int, float, boolean, char
- Name them clearly - ledPin better than x
- You can change them anytime in your code
- Declare once, use many times
- Use
==to compare (not single=) - Curly braces
{}group code that runs together elseis optional - use when you need an alternative actionelse iflets you check multiple conditions in order- Conditions must be true/false (boolean)
- Create a variable called i
- Start it at 0
- This runs only once
- Think of i as a counter
- The loop keeps running while this is true
- When it becomes false, the loop stops
- 0 < 3 (TRUE)
- 1 < 3 (TRUE)
- 2 < 3 (TRUE)
- 3 < 3 (FALSE - STOP)
- After each loop, increase i by 1
- i++ means add 1 to i
- i = 0
- i++ = 1
- i++ = 2
- i++ = 3
- i = 0, print 0
- i = 1, print 1
- i = 2, print 2
- i = 3, print 3
- i = 4, print 4
- i = 5, stop (because 5 < 5 is false)
- Brightness starts at 0
- Increases until 255
- LED slowly gets brighter
- Starts at 10
- Goes DOWN
- Stops at 0
- count-- means subtract 1 each time
- Outer loop runs 3 times
- Inside each of those, inner loop runs 2 times
- Total = 3 x 2 = 6 runs
- Makes code shorter
- Makes code cleaner
- Easy to change number of repetitions
- Perfect for LEDs, motors, arrays, counters, patterns
- for loops repeat code a set number of times
- Initialization: create and start the counter
- Condition: when to stop looping
- Increment: change the counter each time
- Use i++ to count up, i-- to count down
- Loops must eventually become false or they never stop
if Statements
They let your code say: "IF this is true, THEN do something"
Like a fork in the road - Arduino checks a condition and chooses which path to take.
Basic Syntax:
if (condition) {
// Code runs ONLY if condition is true
}
Example: Button Controls LED
void setup() {
pinMode(2, INPUT);
pinMode(13, OUTPUT);
}
void loop() {
int buttonState = digitalRead(2);
if (buttonState == HIGH) {
digitalWrite(13, HIGH); // Only runs if button is pressed
}
}
If-Else: Two Choices
if (condition) {
// Runs if TRUE
} else {
// Runs if FALSE
}
Example:
void loop() {
int buttonState = digitalRead(2);
if (buttonState == HIGH) {
digitalWrite(13, HIGH); // Button pressed β LED ON
} else {
digitalWrite(13, LOW); // Button NOT pressed β LED OFF
}
}
Comparison Operators:
Use these to compare values:
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | if (x == 5) |
!= |
Not equal to | if (x != 5) |
> |
Greater than | if (x > 5) |
< |
Less than | if (x < 5) |
>= |
Greater or equal | if (x >= 5) |
<= |
Less or equal | if (x <= 5) |
Common Mistake:
// WRONG - Single = is assignment, not comparison!
if (x = 5) { // This SETS x to 5, doesn't compare!
}
// CORRECT - Double == compares values
if (x == 5) { // This checks if x equals 5
}
Multiple Conditions with else if:
int sensorValue = analogRead(A0);
if (sensorValue < 300) {
Serial.println("Dark");
} else if (sensorValue < 700) {
Serial.println("Medium light");
} else {
Serial.println("Bright");
}
Logical Operators:
Combine multiple conditions:
&& (AND) - Both must be true
if (buttonState == HIGH && sensorValue > 500) {
// Runs ONLY if button is pressed AND sensor reads above 500
}
|| (OR) - At least one must be true
if (button1 == HIGH || button2 == HIGH) {
// Runs if EITHER button is pressed
}
! (NOT) - Reverses the condition
if (!buttonState) { // Same as: if (buttonState == LOW)
// Runs if button is NOT pressed
}
Practical Example: Temperature Warning
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // Warning LED
}
void loop() {
int tempSensor = analogRead(A0);
int temperature = tempSensor * 0.48; // Convert to Celsius
if (temperature > 30) {
digitalWrite(13, HIGH); // Turn on warning LED
Serial.println("TOO HOT!");
} else if (temperature < 10) {
digitalWrite(13, HIGH); // Turn on warning LED
Serial.println("TOO COLD!");
} else {
digitalWrite(13, LOW); // All good
Serial.println("Temperature OK");
}
delay(1000);
}
Example: Smart LED Brightness
void setup() {
pinMode(9, OUTPUT); // PWM pin
}
void loop() {
int lightLevel = analogRead(A0); // Light sensor (0-1023)
if (lightLevel < 200) {
analogWrite(9, 255); // Dark β LED full brightness
} else if (lightLevel < 500) {
analogWrite(9, 128); // Medium β LED half brightness
} else {
analogWrite(9, 0); // Bright β LED off
}
delay(100);
}
Key Points:
For Loops
What is a For Loop?
A for loop is a way to repeat something a fixed number of times.
Instead of writing the same code again and again, we tell the computer: "Do this ___ times."
Without a Loop (Messy Way)
If you want to blink an LED 3 times:
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
That's a lot of repeated code!
With a For Loop (Clean Way)
for (int i = 0; i < 3; i++) {
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}
Same result. Way shorter. Much cleaner.
How a For Loop Works
Basic structure:
for (initialization; condition; increment) {
// Code to repeat
}
Let's break this down:
for (int i = 0; i < 3; i++)
1. Initialization: int i = 0
2. Condition: i < 3
So it runs while:
3. Increment: i++
Example:
Step-by-Step Example
for (int i = 0; i < 5; i++) {
Serial.println(i);
}
What happens:
Output:
0
1
2
3
4
Real Arduino Examples
Example 1: Blink LED 10 Times
for (int i = 0; i < 10; i++) {
digitalWrite(13, HIGH);
delay(200);
digitalWrite(13, LOW);
delay(200);
}
This means: Blink LED 10 times.
Example 2: Fade LED Slowly
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(9, brightness);
delay(10);
}
Here:
Example 3: Countdown Timer
for (int count = 10; count >= 0; count--) {
Serial.println(count);
delay(1000);
}
This one:
Different Counting Styles
Count by 2
for (int i = 0; i < 10; i += 2)
Prints: 0, 2, 4, 6, 8
Count Backwards
for (int i = 5; i >= 0; i--)
Prints: 5, 4, 3, 2, 1, 0
Nested Loops (Loop Inside Loop)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
Serial.println(j);
}
}
Think of it like:
Why For Loops Are Important
Simple Way to Remember
A for loop is basically saying:
Start here, keep going while this is true, change the counter each time.