I have created a device to fade LED in a sequence with schematic, circuit, codes, a button, for loops, digitalWrite(), digitalRead(), and analogWrite(). I built it with Arduino and implemented it on a breadboard.
According to the schematic, I have built the circuit with Arduino on the breadboard.
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPins[] = {9, 10, 11}; // the number of the LED pins
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// loop through the ledPins array:
for (int i = 0; i < 3; i++) {
// initialize the LED pins as an output:
pinMode(ledPins[i], OUTPUT);
}
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// loop through the ledPins array to fade in each led:
for (int i = 0; i < 3; i++) {
// fade in from min to max in increments of 51 points:
for (int fadeValue = 0; fadeValue <= 255; fadeValue += 51) {
// sets the value (range from 0 to 255):
analogWrite(ledPins[i], fadeValue);
// wait for 10 milliseconds to see the dimming effect
delay(10);
}
}
// loop through the ledPins array to fade out each led:
for (int i = 0; i < 3; i++) {
// fade out from max to min in increments of 51 points:
for (int fadeValue = 255; fadeValue >= 0; fadeValue -= 51) {
// sets the value (range from 0 to 255):
analogWrite(ledPins[i], fadeValue);
// wait for 10 milliseconds to see the dimming effect
delay(10);
}
}
} else {
// loop through ledPins array to turn LED off:
for (int i = 0; i < 3; i++) {
// turn LED off:
digitalWrite(ledPins[i], LOW);
}
}
}