#include <Arduino.h>
// Define the pins where LEDs are connected
const int LED_PIN[4] = {3, 5, 6, 9};
// Declare variables to store brightness and fade direction
byte brightness[4] = {0, 0, 0, 0};
int fadeDirection[4] = {1, 1, 1, 1};
// Declare variables to store glow duration and decay time
unsigned long glowStartTime[4] = {0, 0, 0, 0};
unsigned long decayStartTime[4] = {0, 0, 0, 0};
unsigned long currTime;
// Parameter Settings
const int GLOW_DURATION_MIN = 400; // Minimum glow duration in milliseconds
const int GLOW_DURATION_MAX = 600; // Maximum glow duration in milliseconds
const int DECAY_DURATION_MIN = 400; // Minimum decay duration in milliseconds
const int DECAY_DURATION_MAX = 600; // Maximum decay duration in milliseconds
void setup() {
for (int i = 0; i < 4; i++) {
pinMode(LED_PIN[i], OUTPUT);
}
randomSeed(analogRead(0)); // Seed random function with noise from an unused analog pin
}
void loop() {
currTime = millis(); // Get current time
for (int i = 0; i < 4; i++) {
// If the LED is in its glow phase
if (currTime - glowStartTime[i] < random(GLOW_DURATION_MIN, GLOW_DURATION_MAX)) {
brightness[i] = brightness[i] + (5 * fadeDirection[i]);
// Bound brightness between 0 and 255, and change fade direction if necessary
if (brightness[i] <= 0 || brightness[i] >= 255) {
fadeDirection[i] = -fadeDirection[i];
brightness[i] = constrain(brightness[i], 0, 255);
}
analogWrite(LED_PIN[i], brightness[i]);
} else if (currTime - decayStartTime[i] > random(DECAY_DURATION_MIN, DECAY_DURATION_MAX)) {
// Change to glow phase
glowStartTime[i] = currTime;
fadeDirection[i] = 1;
} else {
// LED is in its decay phase
if (brightness[i] > 0) {
brightness[i] -= 5;
analogWrite(LED_PIN[i], brightness[i]);
} else {
// Change to decay phase
decayStartTime[i] = currTime;
}
}
}
}
In this Arduino sketch, the brightness of 4 LEDs connected to pins 3, 5, 6, and 9 are controlled independently emulating the flickering of coals in a fireplace. The glow and decay times are randomly generated within the defined parameter ranges. The line-by-line comments are added to explain the parameter settings and other essential parts of the code.