int ledPin = 9; // Pin connected to the LED
int brightness = 0; // Initial brightness
int fadeAmount = 5; // How much to increase/decrease brightness
void setup() {
pinMode(ledPin, OUTPUT); // Initialize pin 9 as an output
}
void loop() {
analogWrite(ledPin, brightness); // Set the brightness
brightness += fadeAmount; // Change brightness
// Reverse direction if at the ends of the fade
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30); // Pause for 30ms
}
=================
int ledPin = 13; // Pin connected to the LED
int buttonPin = 2; // Pin connected to the button
int buttonState = 0;
void setup() {
pinMode(ledPin, OUTPUT); // Initialize the LED pin as output
pinMode(buttonPin, INPUT); // Initialize the button pin as input
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the button state
if (buttonState == HIGH) { // If button is pressed
digitalWrite(ledPin, HIGH); // Turn LED on
} else {
digitalWrite(ledPin, LOW); // Turn LED off
}
}
=================
int leds[] = {8, 9, 10}; // Array of LED pins
int numLeds = 3; // Number of LEDs
void setup() {
for (int i = 0; i < numLeds; i++) {
pinMode(leds[i], OUTPUT); // Set each LED pin as output
}
}
void loop() {
for (int i = 0; i < numLeds; i++) {
digitalWrite(leds[i], HIGH); // Turn on LED
delay(500); // Wait
digitalWrite(leds[i], LOW); // Turn off LED
}
}