Imagine you have a box of chocolates, and you want to enjoy them one by one until the box is empty. A ‘for’ loop in the C programming language works a bit like that.
In a ‘for’ loop, you have three important components:
Here’s how it looks in C code:
for (int cookie = 1; cookie <= 10; cookie++) {
Serial.println("Enjoying cookie number " + String(cookie));
}
To gradually change the brightness of an LED, we use a for loop to repeat small steps over time.
Below is the full code to make an LED fade in and out using Pulse Width Modulation (PWM). The LED will gradually brighten, then dim in a loop.
// Lesson 3: Fade LED using PWM
int ledPin = 5; // must be a PWM-capable pin
void setup() {
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
}
void loop() {
// Fade from off to full brightness
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(ledPin, brightness); // Set brightness level
delay(10); // Pause for smooth transition
}
// Fade from full brightness to off
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(ledPin, brightness); // Set brightness level
delay(10); // Pause for smooth transition
}
}
The for loop lets us increase or decrease brightness in tiny steps. The analogWrite() function sends a PWM signal to simulate different voltage levels. Each loop iteration waits 10ms before continuing, making the fade smooth.